上鎖
EX second :設(shè)置鍵的過(guò)期時(shí)間為 second 秒稍浆。 SET key value EX second 效果等同于 SETEX key second value 灼舍。
PX millisecond :設(shè)置鍵的過(guò)期時(shí)間為 millisecond 毫秒烈炭。 SET key value PX millisecond 效果等同于 PSETEX key millisecond value 。
NX :只在鍵不存在時(shí),才對(duì)鍵進(jìn)行設(shè)置操作。 SET key value NX 效果等同于 SETNX key value 语婴。
XX :只在鍵已經(jīng)存在時(shí),才對(duì)鍵進(jìn)行設(shè)置操作驶睦。
public static boolean lock(String key,String lockValue,int expire){
if(null == key){
return false;
}
try {
Jedis jedis = getJedisPool().getResource();
String res = jedis.set(key,lockValue,"NX","EX",expire);
jedis.close();
return res!=null && res.equals("OK");
} catch (Exception e) {
return false;
}
}
lua腳本
if redis.call('get', KEYS[1]) == ARGV[1]
then
return redis.call('del', KEYS[1])
else
return 0
end
釋放鎖
private static final Long lockReleaseOK = 1L;
static String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";// lua腳本砰左,用來(lái)釋放分布式鎖
public static boolean releaseLock(String key ,String lockValue){
if(key == null || lockValue == null) {
return false;
}
try {
Jedis jedis = getJedisPool().getResource();
Object res =jedis.eval(luaScript,Collections.singletonList(key),Collections.singletonList(lockValue));
jedis.close();
return res!=null && res.equals(lockReleaseOK);
} catch (Exception e) {
return false;
}
}
unLock.lua腳本文件
local lockkey = KEYS[1]
--唯一隨機(jī)數(shù)
local uid = KEYS[2]
--失效時(shí)間,如果是當(dāng)前線程场航,也是續(xù)期時(shí)間
local time = KEYS[3]
if redis.call('set',lockkey,uid,'nx','px',time)=='OK' then
return 'OK'
else
if redis.call('get',lockkey) == uid then
if redis.call('EXPIRE',lockkey,time/1000)==1 then
return 'OOKK'
end
end
end
java 調(diào)用腳本文件
public void luaUnLock() throws Exception{
Jedis jedis = new Jedis("localhost") ;
InputStream input = new FileInputStream("unLock.lua");
byte[] by = new byte[input.available()];
input.read(by);
String script = new String(by);
Object obj = jedis.eval(script, Arrays.asList("key","123"), Arrays.asList(""));
System.out.println("執(zhí)行結(jié)果 " + obj);
}
main方法操作
lock("item-01","1",20000);
Thread.sleep(2000);
releaseLock("item-01","1");