redis实现分布式锁的java代码
时间: 2023-08-27 08:05:07 浏览: 82
以下是使用Redis实现分布式锁的Java代码示例:
```java
import redis.clients.jedis.Jedis;
public class RedisDistributedLock {
private Jedis jedis;
private String lockKey;
private int expireTime;
private boolean locked;
public RedisDistributedLock(Jedis jedis, String lockKey, int expireTime) {
this.jedis = jedis;
this.lockKey = lockKey;
this.expireTime = expireTime;
}
public boolean lock() {
long expires = System.currentTimeMillis() + expireTime + 1;
String expiresStr = String.valueOf(expires);
if (jedis.setnx(lockKey, expiresStr) == 1) {
locked = true;
return true;
}
String currentValueStr = jedis.get(lockKey);
if (currentValueStr != null && Long.parseLong(currentValueStr) < System.currentTimeMillis()) {
String oldValueStr = jedis.getSet(lockKey, expiresStr);
if (oldValueStr != null && oldValueStr.equals(currentValueStr)) {
locked = true;
return true;
}
}
return false;
}
public void unlock() {
if (locked) {
jedis.del(lockKey);
locked = false;
}
}
}
```
使用示例:
```java
import redis.clients.jedis.Jedis;
public class Main {
public static void main(String[] args) {
Jedis jedis = new Jedis("localhost");
RedisDistributedLock lock = new RedisDistributedLock(jedis, "mylock", 1000);
try {
if (lock.lock()) {
// do something here
}
} finally {
lock.unlock();
}
}
}
```
注意事项:
- `lockKey` 必须是唯一的,例如使用业务相关的名称加上一个前缀。
- `expireTime` 为锁的过期时间,单位为毫秒。
- 在加锁和解锁时要使用同一个 `RedisDistributedLock` 实例。
- 在使用分布式锁时应该考虑锁的粒度,尽量减小锁的范围,避免锁的竞争。
阅读全文