1、利用hsetnx(设置成功,返回 1 。 如果给定字段已经存在且没有操作被执行,返回 0 )
try{
//防止并发重复充值
if(cacheService.hsetnx(MemberRedisKey.MEMBER_RECHARGE_FLAG, billEntity.getOrderId(), 1)){
memberAccountService.doRechargeHandle(billEntity.getMemberId(), billEntity.getTotalFee());
}else{
logger.info("防止重复充值,订单号:"+billEntity.getOrderId()+"正在充值中");
}
}finally {
cacheService.hdel(MemberRedisKey.MEMBER_RECHARGE_FLAG, billEntity.getOrderId());
}
2、利用incrForTime,可设置过期时间
//防止重复支付
String payLockKey = String.format(MemberRedisKey.MEMBER_PAY_FLAG, serverType + "_" + thirdOrderId);
//60秒过期
if(cacheService.incrForTime(payLockKey, 60) > 1){
throw new AppException("支付处理中");
}
//in插入ForTime源码
public Long incrForTime(String key, long timeout) {
Long ret = this.redisTemplate.opsForValue().increment(key, 1L);
if (ret != null && ret == 1L) {
this.redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
return ret;
}