Java基于数据库、乐观锁、悲观锁、Redis、Zookeeper分布式锁的简单案例实现(保姆级教程)
这里提供一个简化版本的分布式锁实现,使用Redis和ZooKeeper的简单示例。
Redis分布式锁实现:
import redis.clients.jedis.Jedis;
public class RedisDistributedLock {
private Jedis jedis;
private String lockKey;
private int expireTime; // 锁的超时时间
public RedisDistributedLock(Jedis jedis, String lockKey, int expireTime) {
this.jedis = jedis;
this.lockKey = lockKey;
this.expireTime = expireTime;
}
public boolean lock() {
String result = jedis.set(lockKey, "locked", "NX", "PX", expireTime);
return "OK".equals(result);
}
public boolean unlock() {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList("locked"));
return result.equals(1L);
}
}
Zookeeper分布式锁实现:
import org.apache.zookeeper.*;
public class ZkDistributedLock implements Watcher {
private ZooKeeper zk;
private String lockName;
private String waitNode;
public ZkDistributedLock(String hostPort, String lockName) throws Exception {
this.lockName = lockName;
zk = new ZooKeeper(hostPort, 3000, this);
waitNode = zk.create("/locks/" + lockName, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
}
public void lock() throws KeeperException, InterruptedException {
while (true) {
try {
zk.exists("/locks/" + lockName, true);
System.out.println("Waiting for lock...");
synchronized (this) {
wait();
}
System.out.println("Lock acquired");
break;
} catch (KeeperException.NoNodeException e) {
// Lock acquired
break;
}
}
}
public void unlock() throws KeeperException, InterruptedException {
zk.delete(waitNode, -1);
zk.close();
}
@Override
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.NodeDeleted) {
synchronized (this) {
notifyAll();
}
}
}
}
以上代码提供了使用Redis和Zookeeper实现分布式锁的简单示例。在实际应用中,你需要根据具体需求进行安全性和性能的优化,例如使用参数化的Redis命令防止死锁,或者使用Zookeeper的有序节点来实现锁。
评论已关闭