• Java-Redis-Redisson-分布式锁(万能)


    前置

    Java-Redis-Redisson配置基础上我们进行了改造,让锁的使用更加方便

    基础设施

    RedissonLock

    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface RedissonLock {
    
    
        int lockTime() default 3; //加锁的时间默认3秒,  如果任务在3秒内执行完毕那么自动释放锁,如果任务3秒内没有执行完毕也会释放锁, 所以内容执行时间过长适当加大锁的时间
        String key() default "" ;  //唯一标识,如果没有那么默认为token->sessionId
        String doc() default "重复提交请求,请稍后再试";
        boolean repeatLock() default false; //可重复加锁直到加锁成功,默认为false不能重复加锁
        int repeatLockCount() default -1; //可重复加锁限制加锁的次数, 默认-1直到成功,设置10那么加锁10次都没成功就直接返回
        int lockWaitTimeMs() default 100; //重复加锁默认的阻塞时间100毫秒,可以自己定义
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    RepeatSubmitAspect

    import com.application.Result;
    import com.commonutils.NullUtils;
    import com.redis.utils.DistributedRedisLock;
    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.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.util.Assert;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    import javax.servlet.http.HttpServletRequest;
    
    @Aspect
    @Component
    public class RepeatSubmitAspect {
    
        @Value("${spring.redis.redisson.tokenName}")
        private  String tokenName;
    
        @Autowired
        private DistributedRedisLock redisLock;
    
        @Pointcut("@annotation(noRepeatSubmit)")
        public void pointCut(RedissonLock noRepeatSubmit) {
        }
    
        public static HttpServletRequest getRequest() {
            ServletRequestAttributes ra= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            return ra.getRequest();
        }
    
        @Around("pointCut(noRepeatSubmit)")
        public Object around(ProceedingJoinPoint pjp, RedissonLock noRepeatSubmit) throws Throwable {
            int lockSeconds = noRepeatSubmit.lockTime();
            String doc = noRepeatSubmit.doc();
            String keyName = noRepeatSubmit.key();
            boolean b = noRepeatSubmit.repeatLock();
            int repeatLockCount = noRepeatSubmit.repeatLockCount();
            int lockWaitTimeMs = noRepeatSubmit.lockWaitTimeMs();
    
            HttpServletRequest request = getRequest();
            Assert.notNull(request, "request can not null");
    
            //如果没有唯一表示那么就使用token或者sessionID来唯一表示
            if(!NullUtils.notEmpty(keyName)){
                String token = request.getHeader(tokenName);
                if(NullUtils.notEmpty(token)){
                    keyName=token;
                }else{
                    //使用sessionID (注意保证分布式session共享)
                    keyName = request.getSession().getId();
                }
                System.out.println("tokenName:"+keyName);
            }
            String path = request.getServletPath();
            String key = getKey(keyName, path);
            //加锁
            boolean isSuccess = redisLock.acquire(key, lockSeconds,b,repeatLockCount,lockWaitTimeMs);
            if (isSuccess) {
                // 获取锁成功
                Object result;
                try {
                    // 执行
                    result = pjp.proceed();
                } finally {
                    // 解锁
                    redisLock.release(key);
                }
                return result;
    
            } else {
                // 获取锁失败,认为是重复提交的请求
                return Result.Error(doc);
            }
    
        }
    
        private String getKey(String token, String path) {
            return token + path;
        }
    
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88

    DistributedRedisLock

    /**
     * 简要描述
     *
     * @Author: huanmin
     * @Date: 2022/8/1 17:39
     * @Version: 1.0
     * @Description: 文件作用详细描述....
     */
    
    import com.multithreading.utils.SleepTools;
    import lombok.SneakyThrows;
    import org.redisson.api.RLock;
    import org.redisson.api.RedissonClient;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    import java.util.concurrent.TimeUnit;
    
    @Component
    public class DistributedRedisLock {
        private static final Logger logger = LoggerFactory.getLogger(DistributedRedisLock.class);
        //从配置类中获取redisson对象
        @Autowired
        private RedissonClient redissonClient;
        private final String LOCK_TITLE = "redisLock_";
        private final ThreadLocal<Integer> count = new ThreadLocal<>();//计数
    
        //加锁 , 线程加锁的时候发现,锁有人用了 ,那么就会进入自旋等待
        @SneakyThrows
        public boolean acquire(String lockKey, long seconds, boolean repeatLock, int repeatLockCount, int lockWaitTimeMs) {
            count.set(0); //初始化值
            //获取锁对象
            RLock mylock = redissonClient.getLock((LOCK_TITLE + lockKey));
            do {
                //尝试加锁
                boolean b = mylock.tryLock(0, seconds, TimeUnit.SECONDS);;
                if (b) {
                    logger.info("获取锁成功");
                    return true;
                }
                logger.info("尝试获取锁" + Thread.currentThread().getName());
                //获取加锁的次数,如果是-1那么持续加锁,如果满足加锁次数那么结束加锁
                if (repeatLockCount != -1 && count.get().equals(repeatLockCount)) {
                    logger.warn(Thread.currentThread().getName() + "尝试加锁失败以尝试了:" + count.get() + "次");
                    return false;
                }
                SleepTools.ms(lockWaitTimeMs);
                //加锁次数增加
                count.set(count.get() + 1);
            } while (repeatLock);
            logger.warn("重复提交");
            return false;
        }
    
        //手动锁的释放
        public void release(String lockKey) {
            //获取所对象
            RLock mylock = redissonClient.getLock((LOCK_TITLE + lockKey));
            // 这里判断下当前key是否上锁,不然业务执行时间大于锁自动释放时间后,解锁报异常
            if (mylock.isLocked()&&mylock.isHeldByCurrentThread()) { // 是否还是锁定状态并且锁是当前线程的
                    mylock.unlock(); // 释放锁
                    logger.info("解锁:" + lockKey);
            }
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69

    功能使用和介绍

    • 支持配置锁的时间
    • 支持配置锁的key(同一个key的请求会被锁住)
    • 支持重复加锁
    • 支持重复加锁的次数
    • 支持重复加锁的间隔时间

    通过以上功能的的组合能做到,幂等性,分布式悲观锁, 超时丢弃 ,不止在Controller里使用,而是在任何基于Spring容器管理的Bean都支持,当然如果特殊的场景我们可以直接使用DistributedRedisLock类,注意在任何时候都要释放锁

        /***
         *默认加锁3秒
         * 加锁的key为token->sessionId
         * 加锁失败不可重复加锁
         * 默认提示:  重复提交请求,请稍后再试
         */
        @RedissonLock
        @GetMapping(value = "/updateAgeAsyncLock" )
        public Result updateAgeAsyncLock() {
            userService.updateAgeAsyncLock();
            return Result.Ok();
        }
    
        /***
         * 默认加锁3秒
         * 加锁失败不可重复加锁
         * 加锁的key为token->sessionId
         * 提示:  加锁失败
         */
        @RedissonLock(doc = "加锁失败")
        @GetMapping(value = "/updateAgeAsyncLockDoc" )
        public Result updateAgeAsyncLockDoc() {
            userService.updateAgeAsyncLock();
            return Result.Ok();
        }
        /***
         * 默认加锁15秒
         * 加锁失败不可重复加锁
         * 加锁的key为token->sessionId
         * 默认提示:  重复提交请求,请稍后再试
         */
        @RedissonLock(lockTime = 15)
        @GetMapping(value = "/updateAgeAsyncLock0" )
        public Result updateAgeAsyncLock0() {
             userService.updateAgeAsyncLock();
             return Result.Ok();
        }
    
        /***
         * 默认加锁15秒
         * 加锁失败不可重复加锁
         * 加锁的key为updateAgeAsyncLock
         * 默认提示:  重复提交请求,请稍后再试
         */
        @RedissonLock(lockTime = 15,key = "updateAgeAsyncLock")
        @GetMapping(value = "/updateAgeAsyncLock1" )
        public Result updateAgeAsyncLock1() {
            userService.updateAgeAsyncLock();
            return Result.Ok();
        }
        /***
         * 默认加锁15秒
         * 加锁失败可重复加锁,直到加锁成功
         * 加锁的key为updateAgeAsyncLock
         * 默认提示:  重复提交请求,请稍后再试
         */
        @RedissonLock(lockTime = 15,key = "updateAgeAsyncLock",repeatLock = true)
        @GetMapping(value = "/updateAgeAsyncLock2" )
        public Result updateAgeAsyncLock2() {
            userService.updateAgeAsyncLock();
            return Result.Ok();
        }
    
        /***
         * 默认加锁15秒
         * 加锁失败可重复加锁10次,每次默认间隔100毫秒
         * 加锁的key为updateAgeAsyncLock
         * 默认提示:  重复提交请求,请稍后再试
         */
        @RedissonLock(lockTime = 15,key = "updateAgeAsyncLock",repeatLock = true,repeatLockCount = 10)
        @GetMapping(value = "/updateAgeAsyncLock3" )
        public Result updateAgeAsyncLock3() {
            userService.updateAgeAsyncLock();
            return Result.Ok();
        }
        /***
         * 默认加锁15秒
         * 加锁失败可重复加锁10次,每次默认间隔500毫秒
         * 加锁的key为updateAgeAsyncLock
         * 默认提示:  重复提交请求,请稍后再试
         */
        @RedissonLock(lockTime = 15,key = "updateAgeAsyncLock",repeatLock = true,repeatLockCount = 10,lockWaitTimeMs = 500)
        @GetMapping(value = "/updateAgeAsyncLock4" )
        public Result updateAgeAsyncLock4() {
            userService.updateAgeAsyncLock();
            return Result.Ok();
        }
        /***
         * 默认加锁15秒
         * 加锁失败可重复加锁,直到成功,每次尝试间隔500毫秒
         * 加锁的key为updateAgeAsyncLock
         * 默认提示:  重复提交请求,请稍后再试
         */
        @RedissonLock(lockTime = 15,key = "updateAgeAsyncLock",repeatLock = true,lockWaitTimeMs = 500)
        @GetMapping(value = "/updateAgeAsyncLock4" )
        public Result updateAgeAsyncLock4() {
            userService.updateAgeAsyncLock();
            return Result.Ok();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99

    验证方式: 使用jmeter多线程10000请求 ,注意使用jmeter的时候不要使用默认锁key的方式,因为jmeter每次请sessionID都不同的,想要验证效果我们需要手动加key或者使用token

    其他悲观锁的实现方式

    public class DistributedRedisLock {
        //从配置类中获取redisson对象
        @Autowired
        private RedissonClient redissonClient;
        private  final String LOCK_TITLE = "redisLock_";
        //加锁 , 线程加锁的时候发现,锁有人用了 ,那么就会进入自旋等待
        public  boolean acquire(String lockName){
            //声明key对象
            String key = LOCK_TITLE + lockName;
    
            //获取锁对象
            RLock mylock = redissonClient.getLock(key);
            //一直等待直到加锁成功后,并且设置锁过期时间,防止死锁的产生
            mylock.lock(10, TimeUnit.SECONDS);
            System.err.println("======lock======"+Thread.currentThread().getName());
            //加锁成功
            return  true;
        }
        //锁的释放
        public    void release(String lockName){
            //必须是和加锁时的同一个key
            String key = LOCK_TITLE + lockName;
            //获取所对象
            RLock mylock = redissonClient.getLock(key);
         // 这里判断下当前key是否上锁,不然业务执行时间大于锁自动释放时间后,解锁报异常
            if(mylock.isLocked()){ // 是否还是锁定状态
                if(mylock.isHeldByCurrentThread()){ // 时候是当前执行线程的锁
                    mylock.unlock(); // 释放锁
                    System.err.println("======unlock======"+Thread.currentThread().getName());
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    在这里插入图片描述

    点赞 -收藏-关注-便于以后复习和收到最新内容
    有其他问题在评论区讨论-或者私信我-收到会在第一时间回复
    在本博客学习的技术不得以任何方式直接或者间接的从事违反中华人民共和国法律,内容仅供学习、交流与参考
    免责声明:本文部分素材来源于网络,版权归原创者所有,如存在文章/图片/音视频等使用不当的情况,请随时私信联系我、以迅速采取适当措施,避免给双方造成不必要的经济损失。
    感谢,配合,希望我的努力对你有帮助^_^
  • 相关阅读:
    基于长短期神经网络铜期货价格预测,基于LSTM的铜期货价格预测,LSTM的详细原理
    selenium打开火狐浏览器
    【linux】awk常用处理文件命令示例-替换/格式化/条件选择/求和/正则/子字符串
    技术干货|昇思MindSpore 1.5版本中的亲和算法库——MindSpore Boost
    elasticsearch聚合之bucket terms聚合
    基于小程序车辆违章停放执法移动APP-计算机毕业设计源码+LW文档
    基于启发式搜索的一字棋
    MySQL SQL语句与事务执行及日志分析
    《MongoDB入门教程》第07篇 CRUD之查找文档
    http进一步认识
  • 原文地址:https://blog.csdn.net/weixin_45203607/article/details/126124007