Redisを使って分散ロックを実現
/**
* Redis
* SET resource-name anystring NX EX max-lock-time
*
* Redis SET 。
* http://doc.redisfans.com/string/set.html
*
* , Redis 2.6.12 SET ,
* SET key value [EX seconds] [PX milliseconds] [NX|XX], :
*
* EX seconds — key ;
* PX milliseconds — key ;
* NX — key value , key , SETNX。
* XX — key value , key , SETEX。
*
* SET resource-name anystring NX EX max-lock-time Redis 。
*
* :
*
* OK , 。
* NIL , , 。
*
* @author zsy
* @version 1.0
* @date 2019 8 22 22:21:27
*/
public class RedisLock {
private static Logger logger = LoggerFactory.getLogger(RedisLock.class);
private RedisTemplate redisTemplate;
/**
* key value , key , SETNX。
*/
public static final String NX = "NX";
/**
* seconds — key , EXPIRE key seconds
*/
public static final String EX = "EX";
/**
* set
*/
public static final String OK = "OK";
/**
* (ms )
*/
private static final long TIME_OUT = 100;
/**
* (s)
*/
public static final int EXPIRE = 60;
/**
* lua
*/
public static final String UNLOCK_LUA;
static {
StringBuilder sb = new StringBuilder();
sb.append("if redis.call(\"get\",KEYS[1]) == ARGV[1] ");
sb.append("then ");
sb.append(" return redis.call(\"del\",KEYS[1]) ");
sb.append("else ");
sb.append(" return 0 ");
sb.append("end ");
UNLOCK_LUA = sb.toString();
}
/**
* key
*/
private String lockKey;
/**
* key
*/
private String lockKeyLog = "";
/**
*
*/
private String lockValue;
/**
* (s)
*/
private int expireTime = EXPIRE;
/**
* (ms)
*/
private long timeOut = TIME_OUT;
/**
*
*/
private volatile boolean locked = false;
final Random random = new Random();
/**
*
*
* @param redisTemplate
* @param lockKey key(Redis Key)
*/
public RedisLock(RedisTemplate redisTemplate, String lockKey) {
this.redisTemplate = redisTemplate;
this.lockKey = lockKey + "_lock";
}
/**
* ,
*
* @param redisTemplate
* @param lockKey key(Redis Key)
* @param expireTime ( : )
*/
public RedisLock(RedisTemplate redisTemplate, String lockKey, int expireTime) {
this(redisTemplate, lockKey);
this.expireTime = expireTime;
}
/**
* ,
*
* @param redisTemplate
* @param lockKey key(Redis Key)
* @param timeOut ( : )
*/
public RedisLock(RedisTemplate redisTemplate, String lockKey, long timeOut) {
this(redisTemplate, lockKey);
this.timeOut = timeOut;
}
/**
*
*
* @param redisTemplate
* @param lockKey key(Redis Key)
* @param expireTime ( : )
* @param timeOut ( : )
*/
public RedisLock(RedisTemplate redisTemplate, String lockKey, int expireTime, long timeOut) {
this(redisTemplate, lockKey, expireTime);
this.timeOut = timeOut;
}
/**
*
*
* @return
*/
public boolean tryLock() {
// key
lockValue = UUID.randomUUID().toString();
// ,
long timeout = timeOut * 1000000;
// ,
long nowTime = System.nanoTime();
while ((System.nanoTime() - nowTime) < timeout) {
if (OK.equalsIgnoreCase(this.set(lockKey, lockValue, expireTime))) {
locked = true;
//
return locked;
}
//
seleep(10, 50000);
}
return locked;
}
/**
*
*
* @return
*/
public boolean lock() {
lockValue = UUID.randomUUID().toString();
// ( ms)
String result = set(lockKey, lockValue, expireTime);
locked = OK.equalsIgnoreCase(result);
return locked;
}
/**
*
*
* @return
*/
public boolean lockBlock() {
lockValue = UUID.randomUUID().toString();
while (true) {
// ( ms)
String result = set(lockKey, lockValue, expireTime);
if (OK.equalsIgnoreCase(result)) {
locked = true;
return locked;
}
//
seleep(10, 50000);
}
}
/**
*
*
* , :
*
* , (non-guessable) , (token)。
* DEL , Lua , , 。
* 。
*/
public Boolean unlock() {
//
//
if (locked) {
return (Boolean) redisTemplate.execute(new RedisCallback() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
Object nativeConnection = connection.getNativeConnection();
Long result = 0L;
List keys = new ArrayList<>();
keys.add(lockKey);
List values = new ArrayList<>();
values.add(lockValue);
//
if (nativeConnection instanceof JedisCluster) {
result = (Long) ((JedisCluster) nativeConnection).eval(UNLOCK_LUA, keys, values);
}
//
if (nativeConnection instanceof Jedis) {
result = (Long) ((Jedis) nativeConnection).eval(UNLOCK_LUA, keys, values);
}
if (result == 0 && !StringUtils.isEmpty(lockKeyLog)) {
logger.info("Redis , {} ! :{}", lockKeyLog, System.currentTimeMillis());
}
locked = result == 0;
return result == 1;
}
});
}
return true;
}
/**
* redisTemplate set
*
* SET resource-name anystring NX EX max-lock-time Redis 。
*
* :
*
* OK , 。
* NIL , , 。
*
* @param key Key
* @param value
* @param seconds ( )
* @return
*/
private String set(final String key, final String value, final long seconds) {
Assert.isTrue(!StringUtils.isEmpty(key), "key ");
return (String) redisTemplate.execute(new RedisCallback() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
Object nativeConnection = connection.getNativeConnection();
String result = null;
if (nativeConnection instanceof JedisCommands) {
result = ((JedisCommands) nativeConnection).set(key, value, NX, EX, seconds);
}
if (!StringUtils.isEmpty(lockKeyLog) && !StringUtils.isEmpty(result)) {
logger.info(" {} :{}", lockKeyLog, System.currentTimeMillis());
}
return result;
}
});
}
/**
* @param millis
* @param nanos
* @Title: seleep
* @Description:
* @author yuhao.wang
*/
private void seleep(long millis, int nanos) {
try {
Thread.sleep(millis, random.nextInt(nanos));
} catch (InterruptedException e) {
logger.info(" :", e);
}
}
public String getLockKeyLog() {
return lockKeyLog;
}
public void setLockKeyLog(String lockKeyLog) {
this.lockKeyLog = lockKeyLog;
}
public int getExpireTime() {
return expireTime;
}
public void setExpireTime(int expireTime) {
this.expireTime = expireTime;
}
public long getTimeOut() {
return timeOut;
}
public void setTimeOut(long timeOut) {
this.timeOut = timeOut;
}
}