帮我用java 代码写一个 redis 分布式锁可以吗?
时间: 2024-05-14 22:13:25 浏览: 76
当然可以!以下是样例代码:
```
public class RedisDistributedLock {
private static final int DEFAULT_EXPIRY_TIME_MS = 60 * 1000;
private RedisTemplate<String, String> redisTemplate;
private String lockKey;
private String lockValue;
private int lockExpiryTimeMs;
public RedisDistributedLock(RedisTemplate<String, String> redisTemplate, String lockKey, String lockValue, int lockExpiryTimeMs) {
this.redisTemplate = redisTemplate;
this.lockKey = lockKey;
this.lockValue = lockValue;
this.lockExpiryTimeMs = lockExpiryTimeMs;
}
public RedisDistributedLock(RedisTemplate<String, String> redisTemplate, String lockKey, String lockValue) {
this(redisTemplate, lockKey, lockValue, DEFAULT_EXPIRY_TIME_MS);
}
public boolean acquireLock() {
return redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, Duration.ofMillis(lockExpiryTimeMs));
}
public void releaseLock() {
String value = redisTemplate.opsForValue().get(lockKey);
if (value != null && value.equals(lockValue)) {
redisTemplate.delete(lockKey);
}
}
}
```
希望以上代码能够帮助你实现一个 Redis 分布式锁!
阅读全文