基於Redis的分佈式鎖最佳實踐
歡迎轉載,轉載請註明網址:https://blog.csdn.net/qq_41910280
簡介:本文基於spring data redis完成了redis分佈式鎖, 以及註解實現。Talk is cheap, let’s Getting Started.
1. 環境
redis: 5.0.0
spring data redis:2.1.5
spring boot: 2.1.3.RELEASE
2. 核心代碼
主要注意: 上鎖lock 以及 解鎖unlock 的原子性操作, 以此避免了死鎖或誤刪其他線程或服務所上的鎖
package com.example.lock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
@Component
public class RedisLockTool {
Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
StringRedisTemplate redisTemplate;
/**
* 存放本臺服務器註冊的所有key, 定期對所有的key設置過期時間操作
*/
private Map<String, String> keepAliveLocks = new ConcurrentHashMap<>();
private final Timer timer = new Timer();
private static StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
@Value("${redis.lock.aliveMilis:600000}")
private long aliveMilis;
@Value("${redis.lock.intervalMilis:300000}")
private long intervalMilis;
/**
* 分佈式鎖lock
* @param key 鎖名
* @param id 標識符, 只有同一個id才能解key鎖
* @param expireMilis 超時時間, (expireMilis==-1 && keepAlive=false)表示爲永不過期
* @param keepAlive 是否讓key鎖保持alive
* @return
*/
public Boolean lock(String key, String id, long expireMilis, boolean keepAlive) {
logger.info("lock入參 key={}, id={}, expireMilis={}, keepAlive={}", key, id, expireMilis, keepAlive);
Boolean execute = redisTemplate.execute((RedisCallback<Boolean>) connection -> {
RedisStringCommands redisStringCommands = connection.stringCommands();
Boolean set = redisStringCommands.set(stringRedisSerializer.serialize(key), stringRedisSerializer.serialize(id),
Expiration.milliseconds(expireMilis), RedisStringCommands.SetOption.SET_IF_ABSENT);
connection.close();
return set;
});
logger.info("lock 出參 execute={}",execute);
if (execute && keepAlive) {
keepAliveLocks.put(key, "");
keeplockAlive();
}
return execute;
}
//在bean初始化完成之後啓動timer,在timer任務中給鎖續命
@PostConstruct
private void init() {
timer.schedule(new TimerTask() {
@Override
public void run() {
keeplockAlive();
}
}, 0, intervalMilis);
}
//在銷燬之前將timer取消
@PreDestroy
private void destroy() {
timer.cancel();
}
private void keeplockAlive() {
if (keepAliveLocks.size() > 0) {
for (String key : keepAliveLocks.keySet()) {
redisTemplate.expire(key, aliveMilis, TimeUnit.MILLISECONDS);
}
}
}
/**
* 解鎖 解鈴還需繫鈴人
* @param key 鎖名
* @param id 標識符, id相同才能解鎖
* @return 1.id相同而且key沒有過期 2.key過期id=null 返回true
*/
public boolean unlock(String key, String id) {
/*
必須先從concurrentHashMap中刪除 再刪redis的key
避免其他線程中途剛在redis註冊key就被從concurrentHashMap刪除
*/
String redisId = redisTemplate.opsForValue().get(key);
logger.info("unlock入參 key={}, id={}; redis中id={}", key, id, redisId);
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return '0' end";
if (Objects.equals(id, redisId)) {
keepAliveLocks.remove(key);
/*
不直接使用redisTemplate.delete(key)
因爲可能在delete之前剛好key過期並且key被另一線程或機器註冊導致誤刪
*/
Long execute = redisTemplate.execute((RedisScript<Long>) RedisScript.of(script, Long.class),// java的Long對應redis的integer
// stringRedisSerializer, new GenericJackson2JsonRedisSerializer(),
Collections.singletonList(key), id);
// 與上述方法相同
// Object execute = redisTemplate.execute(
// (RedisConnection connection) -> connection.eval(
// script.getBytes(),
// ReturnType.INTEGER,
// 1,
// key.getBytes(),
// id.getBytes())
// );
logger.info("unlock 出參 execute={}", execute);
return Objects.equals(execute, 1L);
}
return false;
}
}
測試代碼略
…
3. 註解
1.註解類
/**
* 分佈式同步鎖
*/
package com.example.annotation;
import java.lang.annotation.*;
/**
* 分佈式同步鎖
*/
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RedisSynchronized {
String value() default "";
String id() default "no identifier";
long expireMilis() default 60000L;
}
2.處理註解的類
package com.example.annotation;
import com.example.lock.RedisLockTool;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Component
public class RedisLockAutoProxyCreator implements BeanPostProcessor, ApplicationContextAware {
@Autowired
RedisLockTool redisLockTool;
// private Map<String, ReflectiveMethodInvocation> fallbackInvocations = new HashMap<String, ReflectiveMethodInvocation>();
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Class<?> clazz = AopUtils.getTargetClass(bean);
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(RedisSynchronized.class)) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(clazz);
enhancer.setCallback(new RedisLockAnnotationHandler(bean));
return enhancer.create();
}
}
return bean;
}
class RedisLockAnnotationHandler implements InvocationHandler {
private Object o;
RedisLockAnnotationHandler(Object o) {
this.o = o;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (!method.isAnnotationPresent(RedisSynchronized.class)) {
return method.invoke(o, args);
}
RedisSynchronized annotation = method.getAnnotation(RedisSynchronized.class);
String key = annotation.value();
if ("".equals(key)) {
key = method.toGenericString();
}
String id = annotation.id();
long expireMilis = annotation.expireMilis();
for (int i = 0; i < 400; i++) {
boolean locked = redisLockTool.lock(key, id, expireMilis, false);// false避免服務器崩潰造成死鎖
if (locked) {
try {
return method.invoke(o, args);
} finally {
redisLockTool.unlock(key, id);
}
}
Thread.sleep(300);
}
throw new RuntimeException("lock fail, key=" + key);
}
}
}
測試代碼:
@RequestMapping("/annotationTest")
@ResponseBody
@RedisSynchronized("123")
public String annotationTest() throws Exception {
System.out.println("do something");
Thread.sleep(30000);
return "annotationTest over";
}
@RequestMapping("/annotationTest2")
@ResponseBody
@RedisSynchronized("123")
public String annotationTest2() throws Exception {
System.out.println("do something");
Thread.sleep(30000);
return "annotationTest over";
}
就個人而言, 註解沒有直接使用RedisLockTool靈活
參考文獻
1.https://zhuanlan.zhihu.com/p/48156279 (有更完善的註解實現)
2.https://wudashan.cn/2017/10/23/Redis-Distributed-Lock-Implement/
本人郵箱:[email protected] [email protected]
[email protected] 歡迎交流,共同進步。
歡迎轉載,轉載請註明本網址。