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

新增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);
    }
}

新增工具类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();
    }
}

新增哥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);
    }
}

声明分布式锁注解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 "获取分布式锁失败";
}

实现分布式锁切面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;
    }
}

新增个返回实体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);
    }
}

新增实体类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;
}

新增控制器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();
    }
}

最后加上redis的配置application.properties

#****************Redis Config**********************
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=

项目地址

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

请关注我的订阅号

订阅号.png

你可能感兴趣的:(47. 从零开始学springboot: spel结合redisson实现动态参数分布式锁)