/** * 线程局部变量 */ private ThreadLocal<String> lockFlag = new ThreadLocal<String>(); /** * redis分类名 */ private static final String CATEGORY = "creditconsole_distributed_lock"; @Autowired(required = false) @Qualifier("redisStoreClient") private RedisStoreClient redisStoreClient; /** * 超时时间 */ private Integer EXPIRE = 10; /** * 添加锁 * * @param businessType * @param businessId * @return */ public boolean lock(Integer businessType, String businessId) { StoreKey key = new StoreKey(CATEGORY, businessType, businessId); String uuid = UUID.randomUUID().toString(); //将uuid放入线程局部变量,释放锁时从线程变量中取,防止其他线程释放锁 lockFlag.set(uuid); return redisStoreClient.setnx(key, lockFlag.get(), 10); } /** * 释放锁 * * @param businessType * @param businessId * @return */ public boolean unLock(Integer businessType, String businessId) { StoreKey key = new StoreKey(CATEGORY, businessType, businessId); //如果value值相同再释放锁 Boolean result = redisStoreClient.compareAndDelete(key, lockFlag.get()); if (result == false) { log.error("DistributedLock {} release lock {} error", lockFlag.get(), key); } return true; }
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交