使用RedisTemplate的execute的回調方法,里面使用Setnx方法
Setnx就是,如果沒有這個key,那么就set一個key-value, 但是如果這個key已經存在,那么將不會再次設置,get出來的value還是最開始set進去的那個value.
接下來我們用代碼的形式展現:
package com.shuige.components.cache.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* Description: 通用Redis幫助類
* User: zhouzhou
* Date: 2018-09-05
* Time: 15:39
*/
@Component
public class CommonRedisHelper {
//鎖名稱
public static final String LOCK_PREFIX = "redis_lock";
//加鎖失效時間,毫秒
public static final int LOCK_EXPIRE = 300; // ms
@Autowired
RedisTemplate redisTemplate;
/**
* 最終加強分布式鎖
*
* @param key key值
* @return 是否獲取到
*/
public boolean lock(String key){
String lock = LOCK_PREFIX + key;
// 利用lambda表達式
return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
long expireAt = System.currentTimeMillis() + LOCK_EXPIRE + 1;
Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(expireAt).getBytes());
if (acquire) {
return true;
} else {
byte[] value = connection.get(lock.getBytes());
if (Objects.nonNull(value) && value.length > 0) {
long expireTime = Long.parseLong(new String(value));
// 如果鎖已經過期
if (expireTime < System.currentTimeMillis()) {
// 重新加鎖,防止死鎖
byte[] oldValue = connection.getSet(lock.getBytes(), String.valueOf(System.currentTimeMillis() + LOCK_EXPIRE + 1).getBytes());
return Long.parseLong(new String(oldValue)) < System.currentTimeMillis();
}
}
}
return false;
});
}
/**
* 刪除鎖
*
* @param key
*/
public void delete(String key) {
redisTemplate.delete(key);
}
}
如何使用呢,導入工具類后:
CommonRedisHelper redisHelper = new CommonRedisHelper();
boolean lock = redisHelper.lock(key);
if (lock) { // 執行邏輯操作 redisHelper.delete(key); } else { // 設置失敗次數計數器, 當到達5次時, 返回失敗 int failCount = 1; while(failCount <= 5){ // 等待100ms重試 try { Thread.sleep(100l); } catch (InterruptedException e) { e.printStackTrace(); } if (redisHelper.lock(key)){ // 執行邏輯操作 redisHelper.delete(key); }else{ failCount ++; } } throw new RuntimeException("現在創建的人太多了, 請稍等再試"); }
