使用java+springboot+springaop+redistemplate+自定义注解,写一个分布式锁
时间: 2023-05-12 18:06:11 浏览: 92
可以使用 RedisTemplate 实现分布式锁,具体实现步骤如下:
1. 定义一个自定义注解,用于标识需要加锁的方法。
2. 在方法执行前获取锁,执行后释放锁。
3. 使用 RedisTemplate 操作 Redis,实现分布式锁。
下面是示例代码:
```java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DistributedLock {
String key();
long expire() default 30000;
}
@Component
@Aspect
public class DistributedLockAspect {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Around("@annotation(distributedLock)")
public Object doAround(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) throws Throwable {
String key = distributedLock.key();
long expire = distributedLock.expire();
// 获取锁
boolean locked = false;
String lockKey = "lock:" + key;
String lockValue = UUID.randomUUID().toString();
try {
locked = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, expire, TimeUnit.MILLISECONDS);
if (!locked) {
throw new RuntimeException("获取锁失败");
}
// 执行方法
return joinPoint.proceed();
} finally {
// 释放锁
if (locked) {
String value = redisTemplate.opsForValue().get(lockKey);
if (lockValue.equals(value)) {
redisTemplate.delete(lockKey);
}
}
}
}
}
```
在需要加锁的方法上加上 @DistributedLock 注解,指定锁的 key 和过期时间即可。
例如:
```java
@Service
public class UserService {
@Autowired
private UserDao userDao;
@DistributedLock(key = "user:update:${#userId}")
public void updateUser(long userId, String name) {
userDao.updateUser(userId, name);
}
}
```
这样就可以实现分布式锁了。