public class RedisUtil {
private static JedisPool jedisPool;
private static final String LOCK_SUCCESS = "OK";
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";
private static final Long RELEASE_SUCCESS = 1L;
public RedisUtil(JedisPoolConfig config) {
if (jedisPool == null) {
jedisPool = new JedisPool(config, "localhost", 6379, 2000);
}
}
public RedisUtil(JedisPoolConfig config, String host, int port) {
if (jedisPool == null) {
jedisPool = new JedisPool(config, host, port, 2000);
}
}
public RedisUtil(JedisPoolConfig config, String host, int port, int timeout) {
if (jedisPool == null) {
jedisPool = new JedisPool(config, host, port, timeout);
}
}
public RedisUtil(JedisPoolConfig config, String host, int port,
int timeout, String password) {
if (jedisPool == null) {
jedisPool = new JedisPool(config, host, port, timeout, password);
}
}
public RedisUtil(JedisPool pool) {
if (RedisUtil.jedisPool == null) {
RedisUtil.jedisPool = pool;
}
}
/**
* 获取分布式锁
* @param lockKey
* @param requestId
* @param expireTime
* @return
*/
public static boolean getDistributedLock( String lockKey, String requestId, int expireTime) {
Jedis jedis = null;
String result="";
boolean success=false;
try {
jedis = jedisPool.getResource();
result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
if (LOCK_SUCCESS.equals(result)) {
success=true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
jedis.close();
}
return success;
}
/**
* 释放分布式锁
* @param lockKey
* @param requestId
* @return
*/
public static boolean releaseDistributedLock(String lockKey, String requestId) {
Jedis jedis = null;
Object result=null;
boolean success=false;
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
try {
jedis = jedisPool.getResource();
result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
if (RELEASE_SUCCESS.equals(result)) {
success=true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
jedis.close();
}
return success;
}
}
加锁操作解析:
-
第一个为key,我们使用key来当锁,因为key是唯一的。
-
第二个为value,我们传的是requestId,很多童鞋可能不明白,有key作为锁不就够了吗,为什么还要用到value?原因就是我们在上面讲到可靠性时,分布式锁要满足第四个条件解铃还须系铃人,通过给value赋值为requestId,我们就知道这把锁是哪个请求加的了,在解锁的时候就可以有依据。requestId可以使用
UUID.randomUUID().toString()方法生成。 -
第三个为nxxx,这个参数我们填的是NX,意思是SET IF NOT EXIST,即当key不存在时,我们进行set操作;若key已经存在,则不做任何操作;
-
第四个为expx,这个参数我们传的是PX,意思是我们要给这个key加一个过期的设置,具体时间由第五个参数决定。
-
第五个为time,与第四个参数相呼应,代表key的过期时间。
总的来说,执行上面的set()方法就只会导致两种结果:1. 当前没有锁(key不存在),那么就进行加锁操作,并对锁设置个有效期,同时value表示加锁的客户端。2. 已有锁存在,不做任何操作。
解锁操作解析:
可以看到,我们解锁只需要两行代码就搞定了!第一行代码,我们写了一个简单的Lua脚本代码,第二行代码,我们将Lua代码传到jedis.eval()方法里,并使参数KEYS[1]赋值为lockKey,ARGV[1]赋值为requestId。eval()方法是将Lua代码交给Redis服务端执行。
那么这段Lua代码的功能是什么呢?其实很简单,首先获取锁对应的value值,检查是否与requestId相等,如果相等则删除锁(解锁)。那么为什么要使用Lua语言来实现呢?因为要确保上述操作是原子性的。那么为什么执行eval()方法可以确保原子性,源于Redis的特性,下面是官网对eval命令的部分解释:
简单来说,就是在eval命令执行Lua代码的时候,Lua代码将被当成一个命令去执行,并且直到eval命令执行完成,Redis才会执行其他命令。
参考:https://blog.csdn.net/zht741322694/article/details/79290822
来源:oschina
链接:https://my.oschina.net/u/3734816/blog/3121479