Redis因?yàn)榉?wù)端的串行化執(zhí)行命令的特性,又提供了很多原子的get/set的命令,所以很適合用來實(shí)現(xiàn)分布式鎖。網(wǎng)上的實(shí)現(xiàn)很多,但大部分都是很久之前的,下面提供一個使用spring-data-redis的實(shí)現(xiàn)的比較完整的。
分布式鎖的要求
- 提供阻塞和非阻塞的獲取鎖接口
- 鎖超時自動釋放
- 鎖超時被其他客戶端獲取后,原來的鎖持有者不能釋放鎖
Redis實(shí)現(xiàn)
基于以上的要求,redis中實(shí)現(xiàn)方式是:
加鎖:通過set一個key并設(shè)置一個超時。加鎖成功后,返回一個token,釋放鎖時需提供該token。
釋放鎖:首先獲取當(dāng)前key的值,如果key的值和持有的token相同,則刪除key,否則不做任何事情。
代碼實(shí)現(xiàn)
加鎖
public String tryLock(String name, long expire) {
Assert.notNull(name, "Lock name must not be null");
Assert.isTrue(expire>0, "expire must greater than 0");
String token = UUID.randomUUID().toString(); //生成唯一的token
//獲取redis連接
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection conn = factory.getConnection();
try{
//原子操作,如果key不存在則set,并設(shè)置超時時間
Boolean result = conn.set(name.getBytes(Charset.forName("UTF-8")), token.getBytes(Charset.forName("UTF-8")),
Expiration.from(expire, TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.SET_IF_ABSENT);
if(result!=null && result)
return token;
}finally { //釋放連接
RedisConnectionUtils.releaseConnection(conn, factory);
}
return null;
}
首先生成一個token,用來以后做鎖的釋放。
然后借助redis的SET key value PX milliseconds NX命令來設(shè)置鎖,這條命令可以在一個原子操作中實(shí)現(xiàn),如果key不存在則set,并且設(shè)置一個expire的時間。RedisConnection類提供了這個命令的接口。命令返回成功,則返回token,否則返回NULL,表明獲取鎖失敗。
最后,因?yàn)槲覀冏约韩@取的Connection,所以別忘記釋放連接。
【注意】這里的使用
UUID.randomUUID()方法生成的token并不能保證一定唯一。但是對于一般的系統(tǒng)是夠用的,主要是因?yàn)槿绻麅纱紊傻膖oken是一樣的話,只對一個情況有影響,就是獲取鎖的線程1沒有及時釋放鎖,鎖自動超時,然后線程2獲取到鎖,剛好線程2在獲取鎖時生成的token跟線程1是一樣的。這個時候線程1來釋放就會把不屬于它的鎖的釋放掉。這個概率是非常小的。如果你的系統(tǒng)對于唯一性非常敏感的話,需要換個token生成方式,保證唯一。
釋放鎖
public boolean unlock(String name, String token) {
Assert.notNull(name, "Lock name must not be null");
Assert.notNull(token, "Token must not be null");
byte[][] keysAndArgs = new byte[2][];
keysAndArgs[0] = name.getBytes(Charset.forName("UTF-8"));
keysAndArgs[1] = token.getBytes(Charset.forName("UTF-8"));
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection conn = factory.getConnection();
try {
Long result = (Long)conn.scriptingCommands().eval(unlockScript.getBytes(Charset.forName("UTF-8")), ReturnType.INTEGER, 1, keysAndArgs);
if(result!=null && result>0)
return true;
}finally {
RedisConnectionUtils.releaseConnection(conn, factory);
}
return false;
}
釋放鎖需要三步,get->compare->del。由于redis中沒有提供一個原子命令一次把這三件事做了,所以要借助lua腳本來實(shí)現(xiàn),腳本如下(unlockScript變量):
if redis.call("get",KEYS[1]) == ARGV[1]
then
return redis.call("del",KEYS[1])
else
return 0
end
阻塞式加鎖
我們系統(tǒng)中加鎖一般都有需求,如果獲取不到就阻塞一段時間。所以我們可以加一個這種接口,其實(shí)很簡單,就是不斷地循環(huán)調(diào)用tryLock,直到獲取到或者超過時間。
public String lock(String name, long expire, long timeout) throws InterruptedException {
//限制阻塞時間,根據(jù)自己的業(yè)務(wù)系統(tǒng)設(shè)置。如果嘗試加鎖的線程多的話最好不要設(shè)置的太大,要不然會有太多的線程在自旋,耗費(fèi)CPU
Assert.isTrue(timeout>0 && timeout<60000, "timeout must greater than 0 and less than 1 min");
long startTime = System.currentTimeMillis();
String token;
do{
token = tryLock(name, expire);
if(token == null) { //加鎖失敗
if((System.currentTimeMillis()-startTime) > (timeout-50))
break; //超過阻塞時間則跳出
Thread.sleep(50); //等待50ms再試,線程多的話這個值不建議設(shè)置的太小
}
}while(token==null);
return token;
}
【注】上面有兩個時間值,一個是限制客戶端最大阻塞時間,一個是每次自旋前的sleep時間,需要根據(jù)自己的業(yè)務(wù)情況調(diào)整。
鎖的使用
鎖的使用就注意一點(diǎn),將unlock放到finally
String token = null;
try{
token = redisLock.tryLock("lock_name", 10000);
if(token != null)
... //業(yè)務(wù)代碼
} finally {
if(token!=null)
redisLock.unlock("lock_name", token);
}
Redis 2.6.12之前版本加鎖實(shí)現(xiàn)
由于redis在2.6.12版本之后才提供了set key value EX NX命令,所以如果你的redis版本比這個老的話,上面的加鎖方法是不能用的。只能使用setnx + expire兩條命令來實(shí)現(xiàn),可以跟釋放鎖一樣用lua腳本保證原子性。
如果你的redis老到連lua都不支持(是不是需要跟運(yùn)維好好談?wù)劻耍?,?dāng)然方法也不是沒有,就是直接使用上面兩個命令。這樣就有可能出現(xiàn)setnx成功expire失敗的情況,造成鎖一直存在,我們可以用下面的方法解決:
public String tryLock(String name, long expire) {
Assert.notNull(name, "Lock name must not be null");
Assert.isTrue(expire>0, "expire must greater than 0");
String token = UUID.randomUUID().toString();
boolean result = redisTemplate.opsForValue().setIfAbsent(name, token);
if(result) {//成功則設(shè)置ttl
redisTemplate.expire(name, expire, TimeUnit.MILLISECONDS);
return token;
}else { //失敗則檢查一下鎖有沒有設(shè)置ttl,沒有則設(shè)置上
long milliSec = redisTemplate.getExpire(name, TimeUnit.MILLISECONDS);
if (milliSec <= 0) {
redisTemplate.expire(name, expire, TimeUnit.MILLISECONDS);
}
return null;
}
}
顯然上面的方法要繁瑣很多,看看就行了,升級redis才是正道。
【附完整代碼】
@Repository
public class RedisLock {
private static final String unlockScript =
"if redis.call(\"get\",KEYS[1]) == ARGV[1]\n"
+ "then\n"
+ " return redis.call(\"del\",KEYS[1])\n"
+ "else\n"
+ " return 0\n"
+ "end";
private StringRedisTemplate redisTemplate;
public RedisLock(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public String lock(String name, long expire, long timeout) throws InterruptedException {
Assert.isTrue(timeout>0 && timeout<60000, "timeout must greater than 0 and less than 1 min");
long startTime = System.currentTimeMillis();
String token;
do{
token = tryLock(name, expire);
if(token == null) {
if((System.currentTimeMillis()-startTime) > (timeout-50))
break;
Thread.sleep(50); //try 50 per sec
}
}while(token==null);
return token;
}
public String tryLock(String name, long expire) {
Assert.notNull(name, "Lock name must not be null");
Assert.isTrue(expire>0, "expire must greater than 0");
String token = UUID.randomUUID().toString();
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection conn = factory.getConnection();
try{
Boolean result = conn.set(name.getBytes(Charset.forName("UTF-8")), token.getBytes(Charset.forName("UTF-8")),
Expiration.from(expire, TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.SET_IF_ABSENT);
if(result!=null && result)
return token;
}finally {
RedisConnectionUtils.releaseConnection(conn, factory);
}
return null;
}
public boolean unlock(String name, String token) {
Assert.notNull(name, "Lock name must not be null");
Assert.notNull(token, "Token must not be null");
byte[][] keysAndArgs = new byte[2][];
keysAndArgs[0] = name.getBytes(Charset.forName("UTF-8"));
keysAndArgs[1] = token.getBytes(Charset.forName("UTF-8"));
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection conn = factory.getConnection();
try {
Long result = (Long)conn.scriptingCommands().eval(unlockScript.getBytes(Charset.forName("UTF-8")), ReturnType.INTEGER, 1, keysAndArgs);
if(result!=null && result>0)
return true;
}finally {
RedisConnectionUtils.releaseConnection(conn, factory);
}
return false;
}
}
springboot依賴,也可以用spring-data-redis加jedis或者lettuce
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.0.5.RELEASE</version>
</dependency>