使用java+springboot+springaop+redis+自定义注解,写一个分布式锁
时间: 2023-05-12 22:06:11 浏览: 202
详解Java如何实现基于Redis的分布式锁
可以使用 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 的分布式锁。
阅读全文