随笔Java 基于Redis分布式锁
Posted 醇氧
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了随笔Java 基于Redis分布式锁相关的知识,希望对你有一定的参考价值。
定义接口
public interface IDistributedLock
boolean tryLock(String var1, Object var2);
boolean tryLock(String var1, Object var2, int var3);
boolean unLock(String var1, Object var2);
实现类
public class DistributedLockImpl
private static final String lockScript = "local n = redis.call('setnx',KEYS[1],ARGV[1])\\nif n == 1 then redis.call('expire',KEYS[1],ARGV[2]) end\\nreturn n";
@Autowired
private RedisTemplate template;
private int defaultExpireTime = 3;
public DistributedLockImpl()
public boolean tryLock(String busiType, Object key)
return this.tryLock(busiType, key, this.defaultExpireTime);
public boolean tryLock(String busiType, Object key, int expire)
return (Boolean)this.template.execute((jedis) ->
String lockKey = this.getLockKey(busiType, key);
String lockValue = this.getLockValue(busiType, key);
boolean locked = (Long)jedis.eval("local n = redis.call('setnx',KEYS[1],ARGV[1])\\nif n == 1 then redis.call('expire',KEYS[1],ARGV[2]) end\\nreturn n", 1, new String[]lockKey, lockValue, String.valueOf(expire)) > 0L;
return locked;
);
public boolean unLock(String busiType, Object key)
return (Boolean)this.template.execute((jedis) ->
String lockedKey = this.getLockKey(busiType, key);
if (jedis.del(lockedKey) > 0L)
return true;
else
return false;
);
private String getLockKey(String busiType, Object key)
Objects.requireNonNull(busiType);
Objects.requireNonNull(key);
return busiType + "_" + key;
private String getLockValue(String busiType, Object key)
Objects.requireNonNull(busiType);
Objects.requireNonNull(key);
return "lock_" + busiType + "_" + key + "_" + (new SecureRandom()).nextInt();
以上是关于随笔Java 基于Redis分布式锁的主要内容,如果未能解决你的问题,请参考以下文章