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

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;



  • 18
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Redisson 实现分布式锁,具体实现如下: 1. 引入 Redisson 依赖: ```xml <dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.16.1</version> </dependency> ``` 2. 定义自定义注解 `DistributedLock`: ```java @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface DistributedLock { String value() default ""; long leaseTime() default 30L; TimeUnit timeUnit() default TimeUnit.SECONDS; } ``` 3. 在需要加锁的方法上加上 `@DistributedLock` 注解: ```java @Service public class UserService { @DistributedLock("user:#{#userId}") public User getUserById(String userId) { // ... } } ``` 4. 实现 `DistributedLockAspect` 切面: ```java @Aspect @Component public class DistributedLockAspect { private final RedissonClient redissonClient; public DistributedLockAspect(RedissonClient redissonClient) { this.redissonClient = redissonClient; } @Around("@annotation(distributedLock)") public Object around(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) throws Throwable { String lockKey = distributedLock.value(); if (StringUtils.isEmpty(lockKey)) { lockKey = joinPoint.getSignature().toLongString(); } RLock lock = redissonClient.getLock(lockKey); boolean locked = lock.tryLock(distributedLock.leaseTime(), distributedLock.timeUnit()); if (!locked) { throw new RuntimeException("获取分布式锁失败"); } try { return joinPoint.proceed(); } finally { lock.unlock(); } } } ``` 5. 在 `application.yml` 中配置 Redisson: ```yaml spring: redis: host: localhost port: 6379 password: database: 0 redisson: single-server-config: address: redis://${spring.redis.host}:${spring.redis.port} ``` 这样就实现了一个基于 Redis 的分布式锁
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值