其他
Spring Boot + Redis 实现分布式锁,还有谁不会??
新建注解 @interface,在注解里设定入参标志 增加 AOP 切点,扫描特定注解 建立 @Aspect 切面任务,注册 bean 和拦截特定方法 特定方法参数 ProceedingJoinPoint,对方法 pjp.proceed() 前后进行拦截 切点前进行加锁,任务执行后进行删除 key
/**
* 线程池,每个 JVM 使用一个线程去维护 keyAliveTime,定时执行 runnable
*/
private static final ScheduledExecutorService SCHEDULER =
new ScheduledThreadPoolExecutor(1,
new BasicThreadFactory.Builder().namingPattern("redisLock-schedule-pool").daemon(true).build());
static {
SCHEDULER.scheduleAtFixedRate(() -> {
// do something to extend time
}, 0, 2, TimeUnit.SECONDS);
}
拦截注解 @RedisLock,获取必要的参数 加锁操作 续时操作 结束业务,释放锁
public enum RedisLockTypeEnum {
/**
* 自定义 key 前缀
*/
ONE("Business1", "Test1"),
TWO("Business2", "Test2");
private String code;
private String desc;
RedisLockTypeEnum(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
public String getUniqueKey(String key) {
return String.format("%s:%s", this.getCode(), key);
}
}
public class RedisLockDefinitionHolder {
/**
* 业务唯一 key
*/
private String businessKey;
/**
* 加锁时间 (秒 s)
*/
private Long lockTime;
/**
* 上次更新时间(ms)
*/
private Long lastModifyTime;
/**
* 保存当前线程
*/
private Thread currentTread;
/**
* 总共尝试次数
*/
private int tryCount;
/**
* 当前尝试次数
*/
private int currentCount;
/**
* 更新的时间周期(毫秒),公式 = 加锁时间(转成毫秒) / 3
*/
private Long modifyPeriod;
public RedisLockDefinitionHolder(String businessKey, Long lockTime, Long lastModifyTime, Thread currentTread, int tryCount) {
this.businessKey = businessKey;
this.lockTime = lockTime;
this.lastModifyTime = lastModifyTime;
this.currentTread = currentTread;
this.tryCount = tryCount;
this.modifyPeriod = lockTime * 1000 / 3;
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface RedisLockAnnotation {
/**
* 特定参数识别,默认取第 0 个下标
*/
int lockFiled() default 0;
/**
* 超时重试次数
*/
int tryCount() default 3;
/**
* 自定义加锁类型
*/
RedisLockTypeEnum typeEnum();
/**
* 释放时间,秒 s 单位
*/
long lockTime() default 30;
}
Pointcut 设定
/**
* @annotation 中的路径表示拦截特定注解
*/
@Pointcut("@annotation(cn.sevenyuan.demo.aop.lock.RedisLockAnnotation)")
public void redisLockPC() {
}
@Around(value = "redisLockPC()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
// 解析参数
Method method = resolveMethod(pjp);
RedisLockAnnotation annotation = method.getAnnotation(RedisLockAnnotation.class);
RedisLockTypeEnum typeEnum = annotation.typeEnum();
Object[] params = pjp.getArgs();
String ukString = params[annotation.lockFiled()].toString();
// 省略很多参数校验和判空
String businessKey = typeEnum.getUniqueKey(ukString);
String uniqueValue = UUID.randomUUID().toString();
// 加锁
Object result = null;
try {
boolean isSuccess = redisTemplate.opsForValue().setIfAbsent(businessKey, uniqueValue);
if (!isSuccess) {
throw new Exception("You can't do it,because another has get the lock =-=");
}
redisTemplate.expire(businessKey, annotation.lockTime(), TimeUnit.SECONDS);
Thread currentThread = Thread.currentThread();
// 将本次 Task 信息加入「延时」队列中
holderList.add(new RedisLockDefinitionHolder(businessKey, annotation.lockTime(), System.currentTimeMillis(),
currentThread, annotation.tryCount()));
// 执行业务操作
result = pjp.proceed();
// 线程被中断,抛出异常,中断此次请求
if (currentThread.isInterrupted()) {
throw new InterruptedException("You had been interrupted =-=");
}
} catch (InterruptedException e ) {
log.error("Interrupt exception, rollback transaction", e);
throw new Exception("Interrupt exception, please send request again");
} catch (Exception e) {
log.error("has some error, please check again", e);
} finally {
// 请求结束后,强制删掉 key,释放锁
redisTemplate.delete(businessKey);
log.info("release the lock, businessKey is [" + businessKey + "]");
}
return result;
}
解析注解参数,获取注解值和方法上的参数值 redis 加锁并且设置超时时间 将本次 Task 信息加入「延时」队列中,进行续时,方式提前释放锁 加了一个线程中断标志 结束请求,finally 中释放锁
// 扫描的任务队列
private static ConcurrentLinkedQueue<RedisLockDefinitionHolder> holderList = new ConcurrentLinkedQueue();
/**
* 线程池,维护keyAliveTime
*/
private static final ScheduledExecutorService SCHEDULER = new ScheduledThreadPoolExecutor(1,
new BasicThreadFactory.Builder().namingPattern("redisLock-schedule-pool").daemon(true).build());
{
// 两秒执行一次「续时」操作
SCHEDULER.scheduleAtFixedRate(() -> {
// 这里记得加 try-catch,否者报错后定时任务将不会再执行=-=
Iterator<RedisLockDefinitionHolder> iterator = holderList.iterator();
while (iterator.hasNext()) {
RedisLockDefinitionHolder holder = iterator.next();
// 判空
if (holder == null) {
iterator.remove();
continue;
}
// 判断 key 是否还有效,无效的话进行移除
if (redisTemplate.opsForValue().get(holder.getBusinessKey()) == null) {
iterator.remove();
continue;
}
// 超时重试次数,超过时给线程设定中断
if (holder.getCurrentCount() > holder.getTryCount()) {
holder.getCurrentTread().interrupt();
iterator.remove();
continue;
}
// 判断是否进入最后三分之一时间
long curTime = System.currentTimeMillis();
boolean shouldExtend = (holder.getLastModifyTime() + holder.getModifyPeriod()) <= curTime;
if (shouldExtend) {
holder.setLastModifyTime(curTime);
redisTemplate.expire(holder.getBusinessKey(), holder.getLockTime(), TimeUnit.SECONDS);
log.info("businessKey : [" + holder.getBusinessKey() + "], try count : " + holder.getCurrentCount());
holder.setCurrentCount(holder.getCurrentCount() + 1);
}
}
}, 0, 2, TimeUnit.SECONDS);
}
@GetMapping("/testRedisLock")
@RedisLockAnnotation(typeEnum = RedisLockTypeEnum.ONE, lockTime = 3)
public Book testRedisLock(@RequestParam("userId") Long userId) {
try {
log.info("睡眠执行前");
Thread.sleep(10000);
log.info("睡眠执行后");
} catch (Exception e) {
// log error
log.info("has some error", e);
}
return null;
}
2020-04-04 14:55:50.864 INFO 9326 --- [nio-8081-exec-1] c.s.demo.controller.BookController : 睡眠执行前
2020-04-04 14:55:52.855 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 0
2020-04-04 14:55:54.851 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 1
2020-04-04 14:55:56.851 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 2
2020-04-04 14:55:58.852 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 3
2020-04-04 14:56:00.857 INFO 9326 --- [nio-8081-exec-1] c.s.demo.controller.BookController : has some error
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method) [na:1.8.0_221]
新建注解 @interface,在注解里设定入参标志 增加 AOP 切点,扫描特定注解 建立 @Aspect 切面任务,注册 bean 和拦截特定方法 特定方法参数 ProceedingJoinPoint,对方法 pjp.proceed() 前后进行拦截 切点前进行加锁,任务执行后进行删除 key
AOP 的实现和常用方法 定时线程池 ScheduledExecutorService 的使用和参数含义 线程 Thread#interrupt 的含义以及用法(这个挺有意思的,可以深入再学习一下)
https://blog.csdn.net/XWForever/article/details/103163021 https://www.zhihu.com/question/41048032
END
往期精彩重试框架 Spring-Retry 和 Guava-Retry,你知道该怎么选吗?
公司新来一个同事,把 @Transactional 事务注解运用得炉火纯青!
Java 近期大事汇总:JDK 19-RC1、Spring 更新、Payara 等
Spring 最常用的 7 大类注解,史上最强整理!
关注后端面试那些事,回复【2022面经】
获取最新大厂Java面经