1.背景
有些业务请求,属于耗时操作,需要加锁,防止后续的并发操作,同时对数据库的数据进行操作,需要
避免对之前的业务造成影响。
2.分析流程
使用 Redis 作为分布式锁,将锁的状态放到 Redis 统一维护,解决集群中单机 JVM 信息不互通的问
题,规定操作顺序,保护用户的数据正确。
梳理设计流程
1. 新建注解 @interface,在注解里设定入参标志
2. 增加 AOP 切点,扫描特定注解
3. 建立 @Aspect 切面任务,注册 bean 和拦截特定方法
4. 特定方法参数 ProceedingJoinPoint,对方法 pjp.proceed() 前后进行拦截
5. 切点前进行加锁,任务执行后进行删除 key
3.业务属性枚举设定
@Getter
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 getUniqueKey(String key){
return String.format("%s:%s",this.getCode(),key);
}
}
4.自定义redis锁注解
import com.example.redislock.enums.RedisLockTypeEnum;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
@Documented
public @interface RedisLockAnnotation {
/**
* 特定参数识别,默认取第 0 个下标
*/
int lockFiled() default 0;
/**
* 超时重试次数
*/
int tryCount() default 3;
/**
* 自定义加锁类型
*/
RedisLockTypeEnum typeEnum();
/**
* 释放时间,秒 s 单位
*/
long lockTime() default 30;
}
5.创建一个任务队列
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class RedisLockDefinitionHolder {
/**
* 业务唯一 key
*/
private String businessKey;
/**
* 加锁时间 (秒 s)
*/
private Long lockTime;
/**
* 上次更新时间(ms)
*/
private Long lastModifyTime;
/**
* 保存当前线程
*/
private Thread currentTread;
/**
* 总共尝试次数
*/
private int tryCount;
/**
设定被拦截的注解名字
核心切面拦截的操作
RedisLockAspect.java 该类分成三部分来描述具体作用
Pointcut 设定
* 当前尝试次数
*/
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;
}
}
6.创建redis锁核心切面拦截
import com.example.redislock.annotation.RedisLockAnnotation;
import com.example.redislock.enums.RedisLockTypeEnum;
import com.example.redislock.task.RedisLockDefinitionHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.UUID;
import java.util.concurrent.*;
@Slf4j
@Aspect
@Component
public class RedisLockAspect {
@Autowired
private RedisTemplate redisTemplate;
@Pointcut("@annotation(com.example.redislock.annotation.RedisLockAnnotation)")
public void redisLockPC(){
}
@Around(value = "redisLockPC()")
public Object around(ProceedingJoinPoint pjp) throws Throwable{
Method method = ((MethodSignature)pjp.getSignature()).getMethod();
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;
}
// 扫描的任务队列
private static ConcurrentLinkedQueue holderList = new
ConcurrentLinkedQueue();
/**
* 线程池,维护keyAliveTime
*/
private static final ScheduledExecutorService SCHEDULER = new ScheduledThreadPoolExecutor(1,
Executors.defaultThreadFactory());
{
// 两秒执行一次「续时」操作
SCHEDULER.scheduleAtFixedRate(() -> {
// 这里记得加 try-catch,否者报错后定时任务将不会再执行=-=
Iterator 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);
}
}
上述流程简单总结一下:
解析注解参数,获取注解值和方法上的参数值
redis 加锁并且设置超时时间
将本次 Task 信息加入「延时」队列中,进行续时,方式提前释放锁
加了一个线程中断标志
结束请求,finally 中释放锁
续时操作
这里用了 ScheduledExecutorService ,维护了一个线程,不断对任务队列中的任务进行判断和延长超时
时间
7.开始测试
import com.example.redislock.annotation.RedisLockAnnotation;
import com.example.redislock.enums.RedisLockTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
public class TestController {
@GetMapping("/testRedisLock")
@RedisLockAnnotation(typeEnum = RedisLockTypeEnum.ONE,lockTime = 3)
public String testRedisLock(@RequestParam("userId") Long userId){
try {
log.info("before");
Thread.sleep(10000);
log.info("after");
}catch (Exception e){
log.info("has some error", e);
}
return null;
}
}
8.测试结果
如果redis加锁时间内多次请求会出现错误提示