1、导入依赖
<dependency><groupId>org.redisson</groupId><artifactId>redisson-spring-boot-starter</artifactId><version>3.10.6</version></dependency><dependency><groupId>org.redisson</groupId><artifactId>redisson</artifactId><version>3.6.1</version></dependency>
2、编写切面,上锁解锁
package com.jsy.config;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.reflect.MethodSignature;import org.redisson.Redisson;import org.redisson.api.RLock;import org.springframework.stereotype.Component;import javax.annotation.Resource;import java.lang.reflect.Method;import java.util.concurrent.TimeUnit;@Aspect@Componentpublic class LockAdvice {@Resourceprivate Redisson rc;@Around("execution(* *..service..*.*(..))&&@annotation(com.jsy.config.RidissonLock)")public Object lock(ProceedingJoinPoint pjp) {System.out.println("加锁成功");RLock lock = null;try {MethodSignature ms = (MethodSignature) pjp.getSignature();Method method = ms.getMethod();RidissonLock rl = method.getDeclaredAnnotation(RidissonLock.class);String className = pjp.getTarget().getClass().getName();//类的绝对路径String methodName = pjp.getSignature().getName(); //方法名lock = rc.getLock(className + ":" + methodName);boolean b = lock.tryLock(rl.time(), rl.lockTimeOut(), TimeUnit.SECONDS);if (b) {return pjp.proceed();}} catch (Throwable e) {e.printStackTrace();throw new RuntimeException(e);} finally {System.out.println("解锁成功");lock.unlock(); // 释放锁}return null;}}
3、自定义注解
package com.jsy.config;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RidissonLock {
// String lockKey();
int time() default 20;
int lockTimeOut() default 20;
String start() default ""; //前缀
String end() default ""; //后缀
int index() default 0; //索引
String fileName() default ""; //字段名
}
4、注册bean
@Bean
public Redisson redisson(){
Config config=new Config();
config.useSingleServer().setAddress("redis://222.178.212.29:6379").setDatabase(11).setPassword("smart99--");
RedissonClient redissonClient = Redisson.create(config);
return (Redisson)redissonClient;
}
