• 47. 从零开始学springboot: spel结合redisson实现动态参数分布式锁


    前言

    随着分布式服务的烂大街, 不可避免的就是公共资源的争用问题, 对开发来说, 本质上就是如何限流加锁的问题.

    上章简单介绍了spel表达式的一些应用案例, 本章则结合spel和redisson来实现一个分布式锁注解.

    Redisson简介

    Redisson 是一个高级的、分布式协调Redis客服端,能帮助用户在分布式环境中轻松实现一些Java的对象.
    Redisson、Jedis、Lettuce 是三个不同的操作 Redis 的客户端.

    Jedis、Lettuce 的 API 更侧重对 Reids 数据库的 CRUD(增删改查),而 Redisson API 侧重于分布式开发.

    关于Redisson的更多介绍大家自行查阅资料了解.

    实例

    引入必要pom依赖 redis、aop、redisson

    
    
        org.springframework.boot
        spring-boot-starter-data-redis
    
    
    
        org.springframework.boot
        spring-boot-starter-aop
    
    
    
        org.redisson
        redisson
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    新增redisson的配置文件RedissonConfig

    @Configuration
    public class RedissonConfig {
    
        @Value("${spring.redis.host}")
        private String host;
    
        @Value("${spring.redis.port}")
        private String port;
    
        @Value("${spring.redis.password}")
        private String password;
    
        @Bean
        @ConditionalOnMissingBean(name = "redisson")
        public Redisson redisson() {
            org.redisson.config.Config config = new org.redisson.config.Config();
            config.useSingleServer().setAddress("redis://" + host + ":" + port);
            return (Redisson) Redisson.create(config);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    新增工具类spel

    public class SpelUtil {
    
        /**
         * 用于SpEL表达式解析.
         */
        private static final SpelExpressionParser parser = new SpelExpressionParser();
    
        /**
         * 用于获取方法参数定义名字.
         */
        private static final DefaultParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer();
    
        /**
         * 解析SpEL表达式
         */
        public static String generateKeyBySpEL(String spELStr, ProceedingJoinPoint joinPoint) {
            // 通过joinPoint获取被注解方法
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            // 使用Spring的DefaultParameterNameDiscoverer获取方法形参名数组
            String[] paramNames = nameDiscoverer.getParameterNames(method);
            // 解析过后的Spring表达式对象
            Expression expression = parser.parseExpression(spELStr);
            // Spring的表达式上下文对象
            EvaluationContext context = new StandardEvaluationContext();
            // 通过joinPoint获取被注解方法的形参
            Object[] args = joinPoint.getArgs();
            // 给上下文赋值
            for (int i = 0; i < args.length; i++) {
                context.setVariable(paramNames[i], args[i]);
            }
            return expression.getValue(context).toString();
        }
    }
    
    • 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

    新增哥aop工具类

    public class AopUtil extends AopUtils {
        /**
         * 判断环绕通知目标方法返回值是否为Void
         *
         * @param joinPoint
         * @return
         */
        public static boolean isReturnVoid(ProceedingJoinPoint joinPoint) {
            Signature signature = joinPoint.getSignature();
            Class returnType = ((MethodSignature) signature).getReturnType();
            return returnType.equals(Void.TYPE);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    声明分布式锁注解DistributedLock

    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface DistributedLock {
    
        /**
         * 锁超时时间【单位秒,默认5秒】
         *
         * @return
         */
        long expireTime() default 5;
    
        /**
         * 分布式缓存Key【SpEL表达式】
         *
         * @return
         */
        String lockKey();
    
        /**
         * 获取锁失败默认提示消息
         *
         * @return
         */
        String message() default "获取分布式锁失败";
    }
    
    • 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

    实现分布式锁切面DistributedLockAop

    @Slf4j
    @Aspect
    @Component
    public class DistributedLockAop {
    
        @PostConstruct
        public void init() {
            log.info("DistributedLockAop init ......");
        }
    
        @Autowired(required = false)
        private Redisson redisson;
    
        private static final String LOCK_KEY_PREFIX = "LOCK:";
    
        /**
         * 拦截加了DistributedTask注解的方法请求
         *
         * @param joinPoint
         * @param distributedLock
         * @return
         * @throws Throwable
         */
        @Around("@annotation(distributedLock)")
        public Object around(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) throws Throwable {
            Object result = null;
    
            String lockKey = LOCK_KEY_PREFIX + SpelUtil.generateKeyBySpEL(distributedLock.lockKey(), joinPoint);
    
            RLock lock = this.redisson.getLock(lockKey);
    
            boolean locked = false;
            try {
                // 尝试获取分布式锁, 并设置超时时间
                locked = lock.tryLock(0, distributedLock.expireTime(), TimeUnit.SECONDS);
                if (!locked) {
                    log.info("#Redisson分布式锁# 加锁失败: [lockKey: {}, ThreadName :{}]", lockKey, Thread.currentThread().getName());
                    // 判断目标方法是否有返回值
                    if (AopUtil.isReturnVoid(joinPoint)) {
                        return null;
                    } else {
                        return R.fail(distributedLock.message());
                    }
                }
                log.info("#Redisson分布式锁# 加锁成功: [lockKey: {}, ThreadName :{}]", lockKey, Thread.currentThread().getName());
    
                // 执行目标方法
                result = joinPoint.proceed();
            } finally {
                if (locked) {
                    lock.unlock();
                    log.info("#Redisson分布式锁# 解锁成功: [lockKey: {}, ThreadName :{}]", lockKey, Thread.currentThread().getName());
                }
            }
            return result;
        }
    }
    
    • 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

    新增个返回实体R

    @Getter
    @Setter
    @NoArgsConstructor
    @JsonSerialize
    @JsonInclude(Include.NON_NULL)
    public class R implements Serializable {
    
        private static final long serialVersionUID = -4888265702222003946L;
    
        // 成功状态码
        public static final Integer SUCCESS_C0DE = Integer.valueOf(0);
    
        // 失败状态码
        public static final Integer FAIL_CODE = Integer.valueOf(-1);
    
        // 接口状态码
        private Integer code;
    
        // 提示消息
        private String message;
    
        // 接口业务数据
        private Object result;
    
        public R(Integer code, String message) {
            super();
            this.code = code;
            this.message = message;
        }
    
        public R(Integer code, Object result) {
            super();
            this.code = code;
            this.result = result;
        }
    
        public R(Integer code) {
            super();
            this.code = code;
        }
    
        public static R success(Object result) {
            return new R(R.SUCCESS_C0DE, result);
        }
    
        public static R success() {
            return new R(R.SUCCESS_C0DE);
        }
    
        public static R fail(String errorMsg) {
            return new R(R.FAIL_CODE, errorMsg);
        }
    
    
        public static R fail(Integer errCode) {
            if (errCode == SUCCESS_C0DE) {
                return new R(FAIL_CODE);
            }
            return new R(errCode);
        }
    
        public static R fail(Integer errCode, String errMessage) {
            return new R(errCode, errMessage);
        }
    }
    
    • 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

    新增实体类user

    @Getter
    @Setter
    @NoArgsConstructor
    @JsonSerialize
    @JsonInclude(Include.NON_NULL)
    public class User implements Serializable {
        private static final long serialVersionUID = -5271056342318564651L;
        private String name;
        private Long id;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    新增控制器DistributedLockController

    @Slf4j
    @RestController
    public class DistributedLockController {
    
        /**
         * 测试:lockKey动态值【SpEL表达式】 + 常量
         */
        @DistributedLock(lockKey = "'userId-' + #userId", expireTime = 100)
        @GetMapping("/lock2/{userId}")
        public R lock2(@PathVariable("userId") Long userId) {
            for (int i = 0; i < 1000000; i++) {
                log.info("waiting......");
            }
            return R.success();
        }
    
    
        /**
         * 测试:lockKey动态值【SpEL表达式】 + 常量
         */
        @DistributedLock(lockKey = "'userId-' + #user.id", expireTime = 100)
        @PostMapping("/lock2")
        public R lock2(@RequestBody User user) {
            for (int i = 0; i < 1000000; i++) {
                log.info("waiting......");
            }
            return R.success();
        }
    }
    
    • 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

    最后加上redis的配置application.properties

    #****************Redis Config**********************
    spring.redis.database=0
    spring.redis.host=127.0.0.1
    spring.redis.port=6379
    spring.redis.password=
    
    • 1
    • 2
    • 3
    • 4
    • 5

    项目地址

    https://github.com/MrCoderStack/SpringBootDemo/tree/master/sb-distributed-lock-annotations

    请关注我的订阅号

    订阅号.png

  • 相关阅读:
    一篇五分生信临床模型预测文章代码复现——Figure 4-6 临床模型构建(四)
    Rust 笔记:Rust 语言中的字符串
    安装elasticsearch8.0.1之后无法访问9200Empty reply from server
    Spring Security系例—漏洞防御
    2010年11月10日 Go生态洞察:回顾Go语言的一年发展
    小白 | 零基础 | 转行 | 六个月 Java 学习路线
    Hadoop3:客户端向HDFS写数据流的流程讲解(较枯燥)
    基于element-plus定义表单配置化
    国内最火热的低代码平台推荐--万界星空科技低代码平台
    C++问答2 三大特性
  • 原文地址:https://blog.csdn.net/MrCoderStack/article/details/126055933