写一段关于分布式锁的Java代码
时间: 2023-08-31 18:28:11 浏览: 153
### 回答1:
示例:public class DistributedLock {
private static final String LOCK_NAME = "lock";
private static final int TIMEOUT = 10000;
public void lock() {
InterProcessMutex lock = new InterProcessMutex(CuratorFramework client, LOCK_NAME);
try {
if (lock.acquire(TIMEOUT, TimeUnit.MILLISECONDS)) {
// 获取分布式锁成功,执行业务逻辑
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
lock.release(); // 释放锁
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
### 回答2:
分布式锁是用于解决分布式环境下的并发访问问题的一种机制。下面是一段使用Java编写的简单分布式锁的示例代码:
```java
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
public class DistributedLockExample {
public static void main(String[] args) {
// 创建Redisson配置
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
RedissonClient redisson = Redisson.create(config);
// 获取分布式锁对象
RLock lock = redisson.getLock("myLock");
try {
// 尝试获取锁,如果已经被其他线程占用,则等待
lock.lock();
// 执行需要保证单线程访问的代码逻辑
System.out.println("Do something...");
} finally {
// 释放锁
lock.unlock();
}
// 关闭Redisson客户端
redisson.shutdown();
}
}
```
上述代码通过使用Redisson客户端库,连接到Redis服务器,并获取一个名为"myLock"的分布式锁对象。在需要保证单线程访问的代码逻辑上锁之后,我们可以在`lock.lock()`和`lock.unlock()`之间执行需要保证单线程访问的业务逻辑。最后,通过调用`redisson.shutdown()`关闭Redisson客户端。使用分布式锁可以保证在分布式环境中的多个线程同时访问临界资源时的数据一致性和并发控制。
### 回答3:
分布式锁是一种用于在分布式系统中实现资源同步的机制。在Java中,我们可以使用Zookeeper或Redis等工具来实现分布式锁。
以下是一个用Java语言实现分布式锁的示例代码:
```java
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.util.concurrent.CountDownLatch;
public class DistributedLock {
private CuratorFramework client;
private String lockPath;
private String lockNode;
private CountDownLatch latch;
public DistributedLock(CuratorFramework client, String lockPath) {
this.client = client;
this.lockPath = lockPath;
this.lockNode = null;
this.latch = new CountDownLatch(1);
}
public void acquireLock() throws Exception {
if (tryLock()) {
return;
}
waitForLock();
acquireLock();
}
private boolean tryLock() throws Exception {
if (lockNode == null) {
lockNode = client.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
.forPath(lockPath + "/lock");
}
String currentNode = lockNode.replace(lockPath + "/", "");
String[] nodes = client.getChildren().forPath(lockPath).toArray(new String[0]);
int index = -1;
for (int i = 0; i < nodes.length; i++) {
if (currentNode.equals(nodes[i])) {
index = i;
break;
}
}
return index == 0;
}
private void waitForLock() throws Exception {
String previousNode = lockPath + "/" + lockNode.replace(lockPath + "/", "").substring(0, lockNode.length() - 10);
ZooKeeper zookeeper = client.getZookeeperClient().getZooKeeper();
Watcher watcher = new Watcher() {
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.NodeDeleted) {
latch.countDown();
}
}
};
if (zookeeper.exists(previousNode, watcher) != null) {
latch.await();
}
}
public void releaseLock() throws KeeperException, InterruptedException {
client.delete().forPath(lockNode);
}
}
```
上述代码使用Curator Framework来与ZooKeeper进行交互,实现了一个简单的分布式锁功能。在`acquireLock`方法中,首先尝试获取锁,如果获取成功则直接返回,否则等待上一个节点释放锁后再次尝试获取。在`tryLock`方法中,通过创建临时有序节点的方式获取锁。在`waitForLock`方法中,使用Watcher监听上一个节点的删除事件,当上一个节点被删除时,通过CountDownLatch来唤醒等待线程。在`releaseLock`方法中,通过删除当前节点来释放锁。
这段代码展示了一个简单的分布式锁实现,供参考和学习使用。实际使用时还需要考虑更多的场景和线程安全问题。
阅读全文