最近因为业务需要用到加锁,所以就想用redis锁,因为对于业务来说,redis锁已经能够满足需求了。
但是,因为需要很多地方需要用到加锁,项目又是基于springboot,所以,就想写个springboot-starter,然后封装个注解,需要的项目中只要引入starter,并且在需要加锁的方法上加上注解就可以了。
1、添加pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</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>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
2、定义锁注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RedisLock {
/**
* 锁key
*/
String key() default "";
/**
* key前缀
*/
String prefix() default "";
/**
* 过期时间,单位毫秒
*/
long expire() default 15000;
/**
* 重试次数
*/
int retryTimes() default 0;
/**
* 重试间隔,单位毫秒
*/
int retryInterval() default 1000;
/**
* 绑定类型(作用于key的生成)
*/
BindType bindType() default BindType.DEFAULT;
/**
* 绑定参数索引,从0开始,与 bindType.ARGS_INDEX 组合使用
*/
int[] bindArgsIndex() default 0;
/**
* 对象参数属性 示例:ClassName.field, 与bingType.OBJECT_PROPERTIES 组合使用
*/
String[] properties() default "";
/**
* 失败策略
*/
ErrorStrategy errorStrategy() default ErrorStrategy.THROW_EXCEPTION;
/**
* 参数key绑定类型
*/
enum BindType {
/**
* 默认,将所有参数toString
*/
DEFAULT,
/**
* 参数索引,从0开始
*/
ARGS_INDEX,
/**
* 对象属性