分布式锁java代码实现
时间: 2024-05-12 13:10:42 浏览: 102
java分布式锁实现代码
分布式锁是一种用于在分布式系统中实现互斥访问的机制。在Java中,可以使用各种技术来实现分布式锁,比如基于数据库、基于缓存、基于ZooKeeper等。下面是一个基于Redis的Java代码示例来实现分布式锁:
```java
import redis.clients.jedis.Jedis;
public class DistributedLock {
private static final String LOCK_KEY = "mylock";
private static final int LOCK_EXPIRE_TIME = 30000; // 锁的过期时间,单位毫秒
private static final int ACQUIRE_TIMEOUT = 5000; // 获取锁的超时时间,单位毫秒
private Jedis jedis;
public DistributedLock(Jedis jedis) {
this.jedis = jedis;
}
public boolean acquireLock() {
long startTime = System.currentTimeMillis();
try {
while (true) {
// 尝试获取锁
String result = jedis.set(LOCK_KEY, "locked", "NX", "PX", LOCK_EXPIRE_TIME);
if ("OK".equals(result)) {
return true; // 获取锁成功
}
// 判断是否超时
long currentTime = System.currentTimeMillis();
if (currentTime - startTime > ACQUIRE_TIMEOUT) {
return false; // 获取锁超时
}
// 等待一段时间后重试
Thread.sleep(100);
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public void releaseLock() {
jedis.del(LOCK_KEY);
}
}
```
使用示例:
```java
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class Main {
public static void main(String[] args) {
JedisPoolConfig config = new JedisPoolConfig();
JedisPool jedisPool = new JedisPool(config, "localhost", 6379);
Jedis jedis = jedisPool.getResource();
DistributedLock lock = new DistributedLock(jedis);
if (lock.acquireLock()) {
try {
// 获取到锁后执行业务逻辑
System.out.println("执行业务逻辑...");
} finally {
lock.releaseLock(); // 释放锁
}
} else {
System.out.println("获取锁超时");
}
jedis.close();
jedisPool.close();
}
}
```
阅读全文