Redisson之——使用Redisson通过自定义注解实现分布式锁,使用Spring AOP简化分布式锁

本文介绍了如何使用Redisson客户端通过自定义注解@DistributedLock实现Java分布式锁,并利用Spring AOP简化加锁逻辑。文中详细展示了自定义注解的定义、切面代码以及在业务代码中的应用,旨在减少重复的锁获取和释放代码,提高代码的可读性和可维护性。
摘要由CSDN通过智能技术生成

lock.lock(leaseTime, timeUnit);

return callback.process();

} finally {

if (lock != null && lock.isLocked()) {

lock.unlock();

}

}

}

@Override

public T tryLock(DistributedLockCallback callback, boolean fairLock) {

return tryLock(callback, DEFAULT_WAIT_TIME, DEFAULT_TIMEOUT, DEFAULT_TIME_UNIT, fairLock);

}

@Override

public T tryLock(DistributedLockCallback callback, long waitTime, long leaseTime, TimeUnit timeUnit, boolean fairLock) {

RLock lock = getLock(callback.getLockName(), fairLock);

try {

if (lock.tryLock(waitTime, leaseTime, timeUnit)) {

return callback.process();

}

} catch (InterruptedException e) {

} finally {

if (lock != null && lock.isLocked()) {

lock.unlock();

}

}

return null;

}

private RLock getLock(String lockName, boolean fairLock) {

RLock lock;

if (fairLock) {

lock = redisson.getFairLock(lockName);

} else {

lock = redisson.getLock(lockName);

}

return lock;

}

public void setRedisson(RedissonClient redisson) {

this.redisson = redisson;

}

}

使用SingleDistributedLockTemplate

DistributedLockTemplate lockTemplate = …;

final String lockName = …;

lockTemplate.lock(new DistributedLockCallback() {

@Override

public Object process() {

//do some business

return null;

}

@Override

public String getLockName() {

return lockName;

}

}, false);

但是每次使用分布式锁都要写类似上面的重复代码,有没有什么方法可以只关注核心业务逻辑代码的编写,即上面的"do some business"。下面介绍如何使用Spring AOP来实现这一目标。

使用Spring AOP简化分布式锁

定义注解@DistributedLock

@Target({ElementType.METHOD})

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface DistributedLock {

/**

  • 锁的名称。

  • 如果lockName可以确定,直接设置该属性。

*/

String lockName() default “”;

/**

  • lockName后缀

*/

String lockNamePre() default “”;

/**

  • lockName后缀

*/

String lockNamePost() default “lock”;

/**

  • 获得锁名时拼接前后缀用到的分隔符

  • @return

*/

String separator() default “.”;

/**

  • 获取注解的方法参数列表的某个参数对象的某个属性值来作为lockName。因为有时候lockName是不固定的。
    
  • 当param不为空时,可以通过argNum参数来设置具体是参数列表的第几个参数,不设置则默认取第一个。
    

*/

String param() default “”;

/**

  • 将方法第argNum个参数作为锁

*/

int argNum() default 0;

/**

  • 是否使用公平锁。

  • 公平锁即先来先得。

*/

boolean fairLock() default false;

/**

  • 是否使用尝试锁。

*/

boolean tryLock() default false;

/**

  • 最长等待时间。

  • 该字段只有当tryLock()返回true才有效。

*/

long waitTime() default 30L;

/**

  • 锁超时时间。

  • 超时时间过后,锁自动释放。

  • 建议:

  • 尽量缩简需要加锁的逻辑。

*/

long leaseTime() default 5L;

/**

  • 时间单位。默认为秒。

*/

TimeUnit timeUnit() default TimeUnit.SECONDS;

}

定义切面代码

@Aspect

@Component

public class DistributedLockAspect {

@Autowired

private DistributedLockTemplate lockTemplate;

@Pointcut(“@annotation(cn.sprinkle.study.distributedlock.common.annotation.DistributedLock)”)

public void DistributedLockAspect() {}

@Around(value = “DistributedLockAspect()”)

public Object doAround(ProceedingJoinPoint pjp) throws Throwable {

//切点所在的类

Class targetClass = pjp.getTarget().getClass();

//使用了注解的方法

String methodName = pjp.getSignature().getName();

Class[] parameterTypes = ((MethodSignature)pjp.getSignature()).getMethod().getParameterTypes();

Method method = targetClass.getMethod(methodName, parameterTypes);

Object[] arguments = pjp.getArgs();

final String lockName = getLockName(method, arguments);

return lock(pjp, method, lockName);

}

@AfterThrowing(value = “DistributedLockAspect()”, throwing=“ex”)

public void afterThrowing(Throwable ex) {

throw new RuntimeException(ex);

}

public String getLockName(Method method, Object[] args) {

Objects.requireNonNull(method);

DistributedLock annotation = method.getAnnotation(DistributedLock.class);

String lockName = annotation.lockName(),

param = annotation.param();

if (isEmpty(lockName)) {

if (args.length > 0) {

if (isNotEmpty(param)) {

Object arg;

if (annotation.argNum() > 0) {

arg = args[annotation.argNum() - 1];

} else {

arg = args[0];

}

lockName = String.valueOf(getParam(arg, param));

} else if (annotation.argNum() > 0) {

lockName = args[annotation.argNum() - 1].toString();

}

}

}

if (isNotEmpty(lockName)) {

String preLockName = annotation.lockNamePre(),

postLockName = annotation.lockNamePost(),

separator = annotation.separator();

StringBuilder lName = new StringBuilder();

if (isNotEmpty(preLockName)) {

lName.append(preLockName).append(separator);

}

lName.append(lockName);

if (isNotEmpty(postLockName)) {

lName.append(separator).append(postLockName);

}

lockName = lName.toString();

return lockName;

}

throw new IllegalArgumentException(“Can’t get or generate lockName accurately!”);

}

/**

  • 从方法参数获取数据

  • @param param

  • @param arg 方法的参数数组

  • @return

*/

public Object getParam(Object arg, String param) {

if (isNotEmpty(param) && arg != null) {

try {

Object result = PropertyUtils.getProperty(arg, param);

return result;

} catch (NoSuchMethodException e) {

throw new IllegalArgumentException(arg + “没有属性” + param + “或未实现get方法。”, e);

} catch (Exception e) {

throw new RuntimeException(“”, e);

}

}

return null;

}

public Object lock(ProceedingJoinPoint pjp, Method method, final String lockName) {

DistributedLock annotation = method.getAnnotation(DistributedLock.class);

boolean fairLock = annotation.fairLock();

boolean tryLock = annotation.tryLock();

if (tryLock) {

return tryLock(pjp, annotation, lockName, fairLock);

} else {

return lock(pjp,lockName, fairLock);

}

}

public Object lock(ProceedingJoinPoint pjp, final String lockName, boolean fairLock) {

return lockTemplate.lock(new DistributedLockCallback() {

@Override

public Object process() {

return proceed(pjp);

}

@Override

public String getLockName() {

return lockName;

}

}, fairLock);

}

public Object tryLock(ProceedingJoinPoint pjp, DistributedLock annotation, final String lockName, boolean fairLock) {

long waitTime = annotation.waitTime(),

leaseTime = annotation.leaseTime();

TimeUnit timeUnit = annotation.timeUnit();

return lockTemplate.tryLock(new DistributedLockCallback() {

@Override

public Object process() {

return proceed(pjp);

}

@Override

public String getLockName() {

return lockName;

}

}, waitTime, leaseTime, timeUnit, fairLock);

}

public Object proceed(ProceedingJoinPoint pjp) {

try {

return pjp.proceed();

} catch (Throwable throwable) {

throw new RuntimeException(throwable);

}

}

private boolean isEmpty(Object str) {

return str == null || “”.equals(str);

}

private boolean isNotEmpty(Object str) {

return !isEmpty(str);

}

}

使用注解@DistributedLock实现分布式锁

有了上面两段代码,以后需要用到分布式锁,只需在核心业务逻辑方法添加注解@DistributedLock,并设置LockName、fairLock等即可。下面的DistributionService演示了多种使用情景。

@Service

public class DistributionService {

@Autowired

private RedissonClient redissonClient;

@DistributedLock(param = “id”, lockNamePost = “.lock”)

public Integer aspect(Person person) {

RMap<String, Integer> map = redissonClient.getMap(“distributionTest”);

Integer count = map.get(“count”);

if (count > 0) {

count = count - 1;

map.put(“count”, count);

}

return count;

}

@DistributedLock(argNum = 1, lockNamePost = “.lock”)

public Integer aspect(String i) {

RMap<String, Integer> map = redissonClient.getMap(“distributionTest”);

Integer count = map.get(“count”);

if (count > 0) {

count = count - 1;

map.put(“count”, count);

}

return count;

}

@DistributedLock(lockName = “lock”, lockNamePost = “.lock”)

public int aspect(Action action) {

return action.action();

}

}

测试

定义一个Worker类:

public class Worker implements Runnable {

private final CountDownLatch startSignal;

private final CountDownLatch doneSignal;

private final DistributionService service;

private RedissonClient redissonClient;

public Worker(CountDownLatch startSignal, CountDownLatch doneSignal, DistributionService service, RedissonClient redissonClient) {

this.startSignal = startSignal;

this.doneSignal = doneSignal;

this.service = service;

this.redissonClient = redissonClient;

}

@Override

public void run() {

try {

startSignal.await();

System.out.println(Thread.currentThread().getName() + " start");

// Integer count = service.aspect(new Person(1, “张三”));

// Integer count = service.aspect(“1”);

Integer count = service.aspect(() -> {

RMap<String, Integer> map = redissonClient.getMap(“distributionTest”);

Integer count1 = map.get(“count”);

if (count1 > 0) {

count1 = count1 - 1;

map.put(“count”, count1);

}

return count1;

});

System.out.println(Thread.currentThread().getName() + ": count = " + count);

doneSignal.countDown();

} catch (InterruptedException ex) {

System.out.println(ex);

}

}

}

定义Controller类:

@RestController

@RequestMapping(“/distributedLockTest”)

public class DistributedLockTestController {

private int count = 10;

@Autowired

private RedissonClient redissonClient;

@Autowired

private DistributionService service;

@RequestMapping(method = RequestMethod.GET)

public String distributedLockTest() throws Exception {

RMap<String, Integer> map = redissonClient.getMap(“distributionTest”);

map.put(“count”, 8);

CountDownLatch startSignal = new CountDownLatch(1);

CountDownLatch doneSignal = new CountDownLatch(count);

for (int i = 0; i < count; ++i) { // create and start threads

new Thread(new Worker(startSignal, doneSignal, service)).start();

}

startSignal.countDown(); // let all threads proceed

doneSignal.await();

System.out.println(“All processors done. Shutdown connection”);

return “finish”;

}

}

Redisson基本配置:

singleServerConfig:

idleConnectionTimeout: 10000

pingTimeout: 1000

connectTimeout: 10000

timeout: 3000

retryAttempts: 3

retryInterval: 1500

reconnectionTimeout: 3000

failedAttempts: 3

password:

subscriptionsPerConnection: 5

clientName: null

address: “redis://127.0.0.1:6379”

subscriptionConnectionMinimumIdleSize: 1

subscriptionConnectionPoolSize: 50

connectionMinimumIdleSize: 10

connectionPoolSize: 64

database: 0

dnsMonitoring: false

dnsMonitoringInterval: 5000

threads: 0

nettyThreads: 0

codec: !<org.redisson.codec.JsonJacksonCodec> {}

useLinuxNativeEpoll: false

工程中需要注入的对象:

@Value(“classpath:/redisson-conf.yml”)

Resource configFile;

@Bean(destroyMethod = “shutdown”)

RedissonClient redisson()

throws IOException {

Config config = Config.fromYAML(configFile.getInputStream());

return Redisson.create(config);

}

@Bean

DistributedLockTemplate distributedLockTemplate(RedissonClient redissonClient) {

return new SingleDistributedLockTemplate(redissonClient);

}

需要引入的依赖:

org.springframework.boot

spring-boot-starter-aop

org.springframework.boot

spring-boot-starter-web

org.redisson

redisson

3.5.3

commons-beanutils

commons-beanutils

1.8.3

最后启动工程,然后访问localhost:8080/distributedLockTest,可以看到如下结果:

分布式锁测试结果

观察结果,可以看出,10个线程中只有8个线程能执行count减1操作,而且多个线程是依次执行的。也就是说分布式锁起作用了。

使用lambda

该注解还可以配合lambda使用。在介绍之前,先科普一下使用spring注解时需要注意的地方,有两点。

第一,在使用spring提供的方法注解时,比较常用的是@Transactional注解。若是Service层不带注解的方法A调用同一个Service类带@Transactional注解的方法B,那么方法B的事务注解将不起作用。比如:

public void methodA() {

methodB();

}

@Transactional

public void methodB() {

// 操作表A

// 操作表B

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip1024b (备注Java)
img

2021年Java中高级面试必备知识点总结

在这个部分总结了2019年到目前为止Java常见面试问题,取其面试核心编写成这份文档笔记,从中分析面试官的心理,摸清面试官的“套路”,可以说搞定90%以上的Java中高级面试没一点难度。

本节总结的内容涵盖了:消息队列、Redis缓存、分库分表、读写分离、设计高并发系统、分布式系统、高可用系统、SpringCloud微服务架构等一系列互联网主流高级技术的知识点。

目录:

(上述只是一个整体目录大纲,每个点里面都有如下所示的详细内容,从面试问题——分析面试官心理——剖析面试题——完美解答的一个过程)

部分内容:

对于每一个做技术的来说,学习是不能停止的,小编把2019年到目前为止Java的核心知识提炼出来了,无论你现在是处于什么阶段,如你所见,这份文档的内容无论是对于你找面试工作还是提升技术广度深度都是完美的。

不想被后浪淘汰的话,赶紧搞起来吧,高清完整版一共是888页,需要的话可以点赞+关注

一个人可以走的很快,但一群人才能走的更远。如果你从事以下工作或对以下感兴趣,欢迎戳这里加入程序员的圈子,让我们一起学习成长!

AI人工智能、Android移动开发、AIGC大模型、C C#、Go语言、Java、Linux运维、云计算、MySQL、PMP、网络安全、Python爬虫、UE5、UI设计、Unity3D、Web前端开发、产品经理、车载开发、大数据、鸿蒙、计算机网络、嵌入式物联网、软件测试、数据结构与算法、音视频开发、Flutter、IOS开发、PHP开发、.NET、安卓逆向、云计算

后续会持续更新**

如果你觉得这些内容对你有帮助,可以添加V获取:vip1024b (备注Java)
[外链图片转存中…(img-i4YXltbX-1712180767267)]

2021年Java中高级面试必备知识点总结

在这个部分总结了2019年到目前为止Java常见面试问题,取其面试核心编写成这份文档笔记,从中分析面试官的心理,摸清面试官的“套路”,可以说搞定90%以上的Java中高级面试没一点难度。

本节总结的内容涵盖了:消息队列、Redis缓存、分库分表、读写分离、设计高并发系统、分布式系统、高可用系统、SpringCloud微服务架构等一系列互联网主流高级技术的知识点。

目录:

[外链图片转存中…(img-NOnKKCN7-1712180767268)]

(上述只是一个整体目录大纲,每个点里面都有如下所示的详细内容,从面试问题——分析面试官心理——剖析面试题——完美解答的一个过程)

[外链图片转存中…(img-cC8L9HeO-1712180767268)]

部分内容:

[外链图片转存中…(img-tKthQywb-1712180767268)]

[外链图片转存中…(img-Z4dcZo95-1712180767269)]

[外链图片转存中…(img-JdmMBl58-1712180767269)]

对于每一个做技术的来说,学习是不能停止的,小编把2019年到目前为止Java的核心知识提炼出来了,无论你现在是处于什么阶段,如你所见,这份文档的内容无论是对于你找面试工作还是提升技术广度深度都是完美的。

不想被后浪淘汰的话,赶紧搞起来吧,高清完整版一共是888页,需要的话可以点赞+关注

一个人可以走的很快,但一群人才能走的更远。如果你从事以下工作或对以下感兴趣,欢迎戳这里加入程序员的圈子,让我们一起学习成长!

AI人工智能、Android移动开发、AIGC大模型、C C#、Go语言、Java、Linux运维、云计算、MySQL、PMP、网络安全、Python爬虫、UE5、UI设计、Unity3D、Web前端开发、产品经理、车载开发、大数据、鸿蒙、计算机网络、嵌入式物联网、软件测试、数据结构与算法、音视频开发、Flutter、IOS开发、PHP开发、.NET、安卓逆向、云计算

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值