/**
* 商家端APP接单
* @param param
* @param userId
* @return
*/
@Override
public Object acceptOrder(acceptOrderDto param, Integer userId) throws Exception {
//1.检查参数
if (param == null || param.getShopId() == null) {
throw new TakeOutException("shopId 为空");
}
// 2. 获取分布式锁,key设置为订单 ID
RLock lock = redissonClient.getLock("order_lock:" + param.getOrderId());
try {
// 2.1 尝试获取锁,等待超时时间30秒
boolean lockAcquired = lock.tryLock(30, TimeUnit.SECONDS);
if (!lockAcquired) {
throw new TakeOutException("获取订单锁失败");
}
//3.得到订单信息
Order order = orderMapper.selectById(param.getOrderId());
//订单不存在
if (order == null) {
throw new TakeOutException("订单不存在");
}
//4.改变订单状态
order.setStatus(2); // 设置订单状态为“已接单”
orderMapper.updateById(order);
//5.返回处理结果
acceptedOrderResp acceptedOrderResp = new acceptedOrderResp();
acceptedOrderResp.setStatus(2);
acceptedOrderResp.setShopId(param.getShopId());
return Result.ok(acceptedOrderResp);
}finally {
// 6. 无论如何,在方法结束时都要释放锁
lock.unlock();
}
}