redisTemplate加锁Demo
2022-06-21 本文已影响0人
赵优秀
/**
* 设备缴费
*
* @param dto
*/
@Override
public boolean payForDevice(TPayCostFlowDTO dto) {
boolean result = false;
//加锁
String key = Constant.PAY_COST_REDIS_LOCK + dto.getDeviceId();
boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", Duration.ofSeconds(30));
if (flag) {
try {
Map<String, Object> deviceMap = tPayCostFlowMapper.getDeviceAmountAndUserInfo(dto.getDeviceId());
String baseAmount = "0.00";
String userAccount = "";
if (null != deviceMap && !deviceMap.isEmpty()) {
Object obj = deviceMap.get("account");
if (null != obj) {
baseAmount = String.valueOf(obj);
}
userAccount = deviceMap.get("userAccount") + "";
}
BigDecimal amount = new BigDecimal(baseAmount);
BigDecimal payAmount = new BigDecimal(dto.getPayAmount());
TPayCostFlow costFlow = new TPayCostFlow();
BigDecimal balanceAmount = payAmount.add(amount);
costFlow.setDeviceId(dto.getDeviceId())
.setPayType(dto.getPayType())
.setPayStatus("1")
.setTradeNo(RedisSerialNoUtil.generateTradeNo(Constant.REDIS_TRADE_NO_KEY))
.setPaySource(dto.getPaySource())
.setPayWay(dto.getPayWay())
.setPayAmount(payAmount)
.setUnit(dto.getUnit())
.setRemark(dto.getRemark())
.setPayTime(LocalDateTime.now())
.setDealUser(getUserName(SecurityUtils.getCurrentUserLogin().get()))
.setPayUser(userAccount)
.setPayBeforeAmount(amount)
.setPayAfterAmount(balanceAmount);
//添加缴费流水信息
tPayCostFlowMapper.insert(costFlow);
//更新设备余额信息
Map<String, Object> map = new HashMap<>();
map.put("id", dto.getDeviceId());
map.put("amount", balanceAmount);
tPayCostFlowMapper.updateDeviceAmount(map);
//添加缴费流水 审核信息 默认未审核状态
TPayCostApproval approval = new TPayCostApproval();
approval.setFlowId(costFlow.getId()).setApprovalStatus("01").setVersion(0);
tPayCostApprovalMapper.insert(approval);
//操作完成 解锁
redisTemplate.opsForValue().getOperations().delete(key);
//添加操作日志
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
SysOperationLogUtils.info(i18nMessage.getMessage("pay.cost.add") + ": " + dto.getDeviceId(), LogEnum.ADD.getKey(), null, this.getClass(), "payForDevice", request);
//缴费成功 且设备余额大于0 result = true;
if (balanceAmount.compareTo(BigDecimal.ZERO) == 1) {
result = true;
}
} catch (Exception e) {
e.printStackTrace();
//操作失败 解锁
redisTemplate.opsForValue().getOperations().delete(key);
throw new BusinessException(i18nMessage.getMessage("error.pay.cost"));
}
} else {
throw new BusinessException(i18nMessage.getMessage("error.pay.lock"));
}
return result;
}