//工具类 public class RedisLock { private static Logger logger = LoggerFactory.getLogger(RedisLock.class); public static void addLock(String key, long timeout) throws BusinessException { logger.info("addLock:key" + key + ",timeout:" + timeout); Jedis jedis = getJedisPool().getResource(); try { String resp = jedis.set("com.zhuoyue.lock."+key, "1", "nx", "ex", timeout); if (resp == null) { throw new BusinessException("99999", "亲,重复提交啦,请" + timeout + "秒后再试"); } } finally { jedis.close(); } } public static void removeLock(String key) { Jedis jedis = getJedisPool().getResource(); try { jedis.del("com.zhuoyue.lock."+key); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { jedis.close(); } } private static JedisPool getJedisPool() { return SpringHelper.getBean(JedisPool.class); } }
//使用
try { RedisLock.addLock(outTradeNo, 60); Map<String, Object> payMap = new HashMap<>(); payMap.put("payNo", "CZ_51_" + tradeNo); Pay pay = payDao.findOneByAttr(payMap); if (pay == null) { logger.error("充值记录不存在,param:{}", JSON.toJSONString(paramsMap)); return "error"; } UserAccountDetail detail = userAccountDetailDao.findUserAccountDetailByOutId("CZ_51_" + tradeNo); if (detail != null) { logger.warn("重复通知,参数:{}", JSON.toJSONString(paramsMap)); return "success"; } userAccountService.addUserAccountBalance(pay.getPayUserId(), null, "CZ_51_"+tradeNo, com.zhuoyue.core.enums.PayType.RECHARGE, Double.parseDouble(totalFee), false); return "success"; } finally { RedisLock.removeLock(outTradeNo); }
//使用很简单,应用场景,同一个账户被多个途径修改,加锁只允许同一时间修改一个,比如转账和被转账,这个时间就应该给这个账户加锁