問題
項目采用spring-boot-starter-data-redis,RedisTemplate中沒有同時設置NX和EX的方法,如果使用setIfAbsent()方法也就是NX,再設置過期時間expire()也就是EX,如果在設置EX時失敗則會造成死鎖。在jedis中提供了同時設置NX和EX的方法,這里通過RedisTemplate的execute()方法獲取Jedis。
存在問題
解決方案可以可以參考Redisson
- 哨兵模式下有問題,Master掛了可能沒有復制到Slave導致鎖丟失
- 如果是多個系統redis配置的庫不同會有問題
- 因為是不公平鎖,所以可能會出現飢餓的情況
- 不支持重入
- 如果執行時間大於鎖過期時間,則會破壞原子性
實現
package com.bailian.scloud.util;
import com.bailian.scloud.service.impl.CloudMbBasicInfoServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisCommands;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
/**
* @program: scloud-support
* @description: Redis鎖
* 不完美可以參考
* @see <a href=https://redis.io/topics/distlock)/>
* @see <a href=https://github.com/redisson/redisson/>
* @author: weijiankai
* @create: 2020-01-15 15:25
**/
//TODO 可以參考Redisson
// 1.哨兵模式下有問題,Master掛了可能沒有復制到Slave導致鎖丟失
// 2.如果是多個系統redis配置的庫不同會有問題
// 3.因為是不公平鎖,所以可能會出現飢餓的情況
// 4.不支持重入
// 5.如果執行時間大於鎖過期時間,則會破壞原子性
public class RedisLockUtil {
private static Logger log = LoggerFactory.getLogger(RedisLockUtil.class);
private static final String LOCK_SUCCESS = "OK";
private static final Long RELEASE_SUCCESS = 1L;
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";
private RedisTemplate redisTemplate;
/**
* 分布式鎖的鍵值
*/
private String lockKey;
/**
* 鎖的超時時間 10s
*/
int expireTime = 10 * 1000;
/**
* 鎖等待,防止線程飢餓 10s
*/
int acquireTimeout = 20 * 1000;
/**
* 獲取指定鍵值的鎖
*
* @param lockKey 鎖的鍵值
*/
public RedisLockUtil(RedisTemplate redisTemplate, String lockKey) {
this.redisTemplate = redisTemplate;
this.lockKey = lockKey;
}
/**
* 獲取指定鍵值的鎖,同時設置獲取鎖超時時間
*
* @param lockKey 鎖的鍵值
* @param acquireTimeout 獲取鎖超時時間
*/
public RedisLockUtil(RedisTemplate redisTemplate, String lockKey, int acquireTimeout) {
this.redisTemplate = redisTemplate;
this.lockKey = lockKey;
this.acquireTimeout = acquireTimeout;
}
/**
* 獲取指定鍵值的鎖,同時設置獲取鎖超時時間和鎖過期時間
*
* @param lockKey 鎖的鍵值
* @param acquireTimeout 獲取鎖超時時間
* @param expireTime 鎖失效時間
*/
public RedisLockUtil(RedisTemplate redisTemplate, String lockKey, int acquireTimeout, int expireTime) {
this.redisTemplate = redisTemplate;
this.lockKey = lockKey;
this.acquireTimeout = acquireTimeout;
this.expireTime = expireTime;
}
public String acquire() {
try {
// 獲取鎖的超時時間,超過這個時間則放棄獲取鎖
long end = System.currentTimeMillis() + acquireTimeout;
// 隨機生成一個value
SnowflakeIdWorkerUtils idWorker = new SnowflakeIdWorkerUtils(0, 1);
String requireToken = idWorker.nextId();
while (System.currentTimeMillis() < end) {
//獲取jedis客戶端,原因redisTemplate沒有同時是指NX和EX的方法
String result = (String) redisTemplate.execute((RedisCallback<String>) connection -> {
JedisCommands commands = (JedisCommands) connection.getNativeConnection();
return commands.set(lockKey, requireToken, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
});
if (LOCK_SUCCESS.equals(result)) {
return requireToken;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} catch (Exception e) {
log.error("acquire lock due to error", e);
}
return null;
}
public boolean release(String identify) {
if (identify == null) {
return false;
}
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = new Object();
try {
result = redisTemplate.execute((RedisCallback<Long>) connection -> {
Object nativeConnection = connection.getNativeConnection();
//集群模式
if (nativeConnection instanceof JedisCluster) {
return (Long) ((JedisCluster) nativeConnection).eval(script, Collections.singletonList(lockKey),
Collections.singletonList(identify));
}// 單機模式
else if (nativeConnection instanceof Jedis) {
return (Long) ((Jedis) nativeConnection).eval(script, Collections.singletonList(lockKey),
Collections.singletonList(identify));
}else {
return 0L;
}
});
if (RELEASE_SUCCESS.equals(result)) {
log.info("release lock success, requestToken:{}", identify);
return true;
}
} catch (Exception e) {
log.error("release lock due to error", e);
}
log.info("release lock failed, requestToken:{}, result:{}", identify, result);
return false;
}
}
