用Java写个分布式锁
时间: 2024-05-03 17:21:11 浏览: 70
以下是一个简单的Java分布式锁实现:
```java
import redis.clients.jedis.Jedis;
public class DistributedLock {
private Jedis jedis;
private String lockKey;
private int expireTime;
private boolean locked = false;
public DistributedLock(Jedis jedis, String lockKey, int expireTime) {
this.jedis = jedis;
this.lockKey = lockKey;
this.expireTime = expireTime;
}
public boolean lock() {
long nowTime = System.currentTimeMillis();
long lockExpireTime = nowTime + expireTime + 1;
String result = jedis.set(lockKey, String.valueOf(lockExpireTime), "NX", "PX", expireTime);
if ("OK".equals(result)) {
locked = true;
return true;
} else {
String lockTimeStr = jedis.get(lockKey);
if (lockTimeStr != null && Long.parseLong(lockTimeStr) >= nowTime) {
return false;
} else {
String oldLockTimeStr = jedis.getSet(lockKey, String.valueOf(lockExpireTime));
if (oldLockTimeStr == null || oldLockTimeStr.equals(lockTimeStr)) {
locked = true;
return true;
} else {
return false;
}
}
}
}
public boolean unlock() {
if (locked) {
jedis.del(lockKey);
locked = false;
return true;
}
return false;
}
}
```
该实现使用Redis作为分布式锁存储介质,利用Redis的SET命令的NX(不存在则设置)选项来实现锁的获取,利用GETSET命令来实现锁的释放。其中,expireTime表示锁的过期时间,单位为毫秒。如果获取锁成功,则返回true,否则返回false。释放锁时,如果当前线程持有锁,则释放锁并返回true,否则返回false。
阅读全文