1 redis分布式锁
/**
* 该方法是原子性
* key:key键
* value:value值
* nxxx:参数是NX,当key存在,不做任何操作,当key不存在,执行set操作
* expx:过期时间单位EX = seconds; PX = milliseconds,数值由下面一个参数决定
* time:过期时间值
*/
public String set(final String key, final String value, final String nxxx, final String expx,
final long time) {
}
package redis.config;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.Collections;
public class RedisLock {
@Autowired
private JedisPool jedisPool;
public boolean lock(String prefix, String key, String value, Long lockWaitTimeOut, Long lockExpireTimeOut){
Jedis jedis = jedisPool.getResource();
try {
jedis = jedisPool.getResource();
String realKey = prefix + key;
Long deadTimeLine = System.currentTimeMillis() + lockWaitTimeOut;
for (;;) {
String result = jedis.set(realKey, value, "NX", "PX", lockExpireTimeOut);
if ("OK".equals(result)) {
return true;
}
lockWaitTimeOut = deadTimeLine - System.currentTimeMillis();
if (lockWaitTimeOut <= 0L) {
return false;
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
jedis.close();
}
return false;
}
/**
* 正确的操作分布式lock
* @param prefix
* @param key
* @param value
* @return
*/
public boolean ulock(String prefix, String key, String value){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String realKey = prefix + key;
//使用lua脚本
String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = jedis.eval(luaScript, Collections.singletonList(realKey),
Collections.singletonList(value));
if ("1".equals(result)) {
return true;
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
jedis.close();
}
return false;
}
}