//加锁
public Boolean tryLock(String key, String value, ExpireTime expire){
return smsRedisService.setIfAbsent(key, value, expire);
}
//解锁
public void unLock(String key){
if(smsRedisService.hasKey(key)){
smsRedisService.delete(key);
}
}
//使用
public WebResultDTO<String> rescueOutStock(RescueOutStockInputBean inputBean, HttpServletRequest request, BindingResult bindingResult){
//入参
LOGGER.info("出库入参 inputBean:{}",inputBean);
if (bindingResult.hasErrors()) {
return new WebResultDTO<>(HttpStatusEnum.BAD_REQUEST.getVal(), null, "参数错误",getErrorMesg(bindingResult));
}
//加锁
Boolean flag = webSysRescueDeliveryService.tryLock(RESCUE_OUT_STOCK_LOCK, String.valueOf(System.currentTimeMillis()), ExpireTime.FIVE_MINUTES);
if(!flag){
return new WebResultDTO<>(HttpStatusEnum.BAD_REQUEST.getVal(), null,"点击的太快了,有正在处理的出库单");
}
//查库
WebResultDTO<String> dto;
try {
dto = webSysRescueDeliveryService.rescueOutStock(inputBean,request);
} catch (RpcException e) {
LOGGER.error("上游服务不可用", e);
return new WebResultDTO<>(HttpStatusEnum.SERVICE_UNAVAILABLE.getVal(), null,"上游服务不可用");
} catch (ErpBusinessException e) {
LOGGER.error("业务异常", e);
return new WebResultDTO<>(e.getCode(), null,e.getMessage());
} catch (Exception e) {
LOGGER.error("未知错误", e);
return new WebResultDTO<>(HttpStatusEnum.NOT_EXTENDED.getVal(), null,"未知错误,请联系客服");
}finally {
//解锁
webSysRescueDeliveryService.unLock(RESCUE_OUT_STOCK_LOCK);
}
//返回
return dto;
}
Redis分布式锁(实例)
于 2021-01-07 14:01:28 首次发布