一、业务配景
有些业务哀求,属于耗时操纵,必要加锁,防止后续的并发操纵,同时对数据库的数据举行操纵,必要克制对之前的业务造成影响。
二、分析流程
使用 Redis 作为分布式锁,将锁的状态放到 Redis 同一维护,办理集群中单机 JVM 信息不互通的题目,规定操纵序次,掩护用户的数据准确。梳理筹划流程
- 新建注解 @interface,在注解里设定入参标志
- 增长 AOP 切点,扫描特定注解
- 创建 @Aspect 切面使命,注册 bean 和拦截特定方法
- 特定方法参数 ProceedingJoinPoint,对方法 pjp.proceed() 前后举行拦截
- 切点前举行加锁,使命实行后举行删除 key
核心步调:加锁、解锁和续时
加
使用了 RedisTemplate 的 opsForValue.setIfAbsent 方法,判定是否有 key,设定一个随机数 UUID.random().toString,天生一个随机数作为 value。从 redis 中获取锁之后,对 key 设定 expire 失效时间,到期后自动开释锁。按照这种筹划,只有第一个乐成设定 Key 的哀求,才华举行后续的数据操纵,后续别的哀求由于无法得到?资源,将会失败竣事。
超时题目
担心 pjp.proceed() 切点实行的方法太耗时,导致 Redis 中的 key 由于超时提前开释了。例如,线程 A 先获取锁,proceed 方法耗时,凌驾了锁超时时间,到期开释了锁,这时另一个线程 B 乐成获取 Redis 锁,两个线程同时对同一批数据举行操纵,导致数据禁绝确。
办理方案:增长一个「续时」
使命不完成,锁不开释:维护了一个定时线程池 ScheduledExecutorService,每隔 2s 去扫描到场队列中的 Task,判定是否失效时间是否快到了,公式为:【失效时间】<= 【当前时间】+【失效隔断(三分之一超时)】
/** * 线程池,每个 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,获取须要的参数
- 加锁操纵
- 续时操纵
- 竣事业务,开释锁
四、实操
之前也有整理过 AOP 使用方法,可以参考一下。
相关属性类设置
业务属性罗列设定
`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;}`核心切面拦截的操纵
RedisLockAspect.java 该类分成三部分来形貌详细作用
Pointcut 设定
/** * @annotation 中的路径表现拦截特定注解 */@Pointcut("@annotation(cn.sevenyuan.demo.aop.lock.RedisLockAnnotation)")public void redisLockPC() {}Around 前后举行加锁和开释锁
前面步调界说了我们想要拦截的切点,下一步就是在切点前后做一些自界说操纵:
@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 中开释锁
续时操纵这里用了 ScheduledExecutorService,维护了一个线程,不停对使命[队列中的使命举行判定和延长超时时间:
`// 扫描的使命队列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);}`这段代码,用来实现筹划图中虚线框的头脑,克制一个哀求非常耗时,导致提前开释了锁。这里加了「线程克制」Thread#interrupt,盼望凌驾重试次数后,能让线程克制**(未经严谨测试,仅供参考哈哈哈哈)不外发起假如遇到这么耗时的哀求,照旧可以或许从根源上查找,分析耗时路径,举行业务优化或别的处理处罚,克制这些耗时操纵。以是记得多办理 Log,分析题目时可以更快一点。怎样使用SpringBoot AOP 记载操纵日记、非常日记?
五、开始测试
在一个入口方法中,使用该注解,然后在业务中模拟耗时哀求,使用了 Thread#sleep
@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;}使用时,在方法上添加该注解,然后设定相应参数即可,根据 typeEnum 可以区分多种业务,限制该业务被同时操纵。测试效果:
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 : 02020-04-04 14:55:54.851 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 12020-04-04 14:55:56.851 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 22020-04-04 14:55:58.852 INFO 9326 --- [k-schedule-pool] c.s.demo.aop.lock.RedisLockAspect : businessKey : [Business1:1024], try count : 32020-04-04 14:56:00.857 INFO 9326 --- [nio-8081-exec-1] c.s.demo.controller.BookController : has some errorjava.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) [na:1.8.0_221]我这里测试的是重试次数过多,失败的场景,假如淘汰睡眠时间,就能让业务正常实行。假如同时哀求,你将会发现以下错误信息:
表现我们的锁?简直收效了,克制了重复哀求。
六、总结
对于耗时业务和核心数据,不能让重复的哀求同时操纵数据,克制数据的不准确,以是要使用分布式锁来对它们举行掩护。再来梳理一下筹划流程:
- 新建注解 @interface,在注解里设定入参标志
- 增长 AOP 切点,扫描特定注解
- 创建 @Aspect 切面使命,注册 bean 和拦截特定方法
- 特定方法参数 ProceedingJoinPoint,对方法 pjp.proceed() 前后举行拦截
- 切点前举行加锁,使命实行后举行删除 key
本次学习是通过 Review 小同伴的代码筹划,从中了解分布式锁的详细实现,仿照他的筹划,重新写了一份简化版的业务处理处罚。对于之前没思量到的「续时」操纵,这里使用了保卫线程来定时判定和延长超时时间,克制了锁提前开释。于是乎,同时回首了三个知识点:1、AOP 的实现和常用方法2、定时线程池 ScheduledExecutorService 的使用和参数寄义3、线程 Thread#interrupt 的寄义以及用法(这个挺故意思的,可以深入再学习一下) |