简介
Redisson在我们的开发场景中,使用不少,一般是使用redissonClient编写方法,可能会和业务代码写在一起,所以为了减少耦合性,使用注解和切面将其抽取出来
实现方式
1、引入依赖
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.13.6</version>
</dependency>
<!-- 切面依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.0.M1</version>
</dependency>
2、注解编写RedissonLock
package com.walker.redisson.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;
/**
* @author: walker
* time: 2024/6/14
* description: 分布式锁
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RedissonLock {
// key的组成: prefix+suffix
/**
* key的前缀,默认取方法全限定名,除非我们在不同方法上对同一个资源做分布式锁,就自己指定
*/
String prefixKey() default "";
/**
* 分布式锁的key 支持spring el表达式
*/
String suffixKey();
/**
* 分隔符
*/
String delimiter() default ":";
/**
* 是否阻塞等待
*/
boolean isBlock() default false;
/**
* 等待时长 默认不等待
*/
int waitTime() default 0;
/**
* 释放时间
* 对时间没有把握的,可以不使用。使用看门狗的机制进行
*/
int leaseTime() default 100;
/**
* 时间单位
*/
TimeUnit timeUnit() default TimeUnit.SECONDS;
}
3、Redisson配置类
创建Redisson的客户端连接对象
引入的是spring redis的Properties,方便和redis同步使用
注意:记得设置database 否则database会默认使用0,如果生产环境可能会影响
package com.walker.redisson.config;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.

最低0.47元/天 解锁文章
676

被折叠的 条评论
为什么被折叠?



