什么叫做分布式锁呢?
比如说"进程 1"在使用该资源的时候,会先去获得锁,"进程 1"获得锁以后会对该资源保持独占,这样其他进程就无法访问该资源,"进程 1"用完该资源以后就将锁释放掉,让其他进程来获得锁,那么通过这个锁机制,我们就能保证了分布式系统中多个进程能够有序的访问该临界资源。那么我们把这个分布式环境下的这个锁叫作分布式锁。
1)分布式锁实现
package com.gk.case2;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/**
* create with IntelliJ IDEA
*
* @Project :zookeeper
* @Package :com.gk.case2
* @ClassName :
* @CreateTime :2022/4/129:34
* @Version :1.0
* @Author :锦林
* @Email :[email protected]
**/
public class DistributedLock {
private final String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
private final int sessionTimeout = 2000;
private final ZooKeeper zk;
private String rootNode = "locks";
private String subNode = "seq-";
// Zookeeper连接
private CountDownLatch connectLatch = new CountDownLatch(1);
// Zookeeper节点等待
private CountDownLatch waitLatch = new CountDownLatch(1);
// 当前client等待的子节点
private String waitPath;
// 当前client创建的子节点
private String currentNode;
// 和zk服务建立连接,并创建根节点
public DistributedLock() throws IOException, InterruptedException, KeeperException {
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
public void process(WatchedEvent watchedEvent) {
// 连接建立时,打开latch,唤醒wait在该latch上的线程
if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
connectLatch.countDown();
}
// 发生了waitPath的删除事件
if (watchedEvent.getType() == Event.EventType.NodeDeleted && watchedEvent.getPath().equals(waitPath)) {
waitLatch.countDown();
}
}
});
// 等待连接建立
connectLatch.await();
// 获取根节点状态
Stat stat = zk.exists("/" + rootNode, false);
// 如果根节点不存在,则创建根节点,根节点类型为永久节点
if (stat == null) {
System.out.println("根节点不存在");
zk.create("/" + rootNode, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
}
// 加锁方法
public void zkLock() {
try {
// 在根节点下创建临时顺序节点,返回值为创建的节点路径
currentNode = zk.create("/" + rootNode + "/" + subNode, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
// wait一会,让结果更清晰一些
Thread.sleep(10);
// 注意,没有必要监听“/locks”的子节点的变化情况
List children = zk.getChildren("/" + rootNode, false);
// 列表中只有一个子节点,那肯定就是currentNode,说明client获得锁
if (children.size() == 1) {
return;
} else {
// 对根节点下的所有临时顺序节点进行从小到大排序
Collections.sort(children);
// 当前节点名称
String thisNode = currentNode.substring(("/" + rootNode + "/").length());
// 获取当前节点的位置
int index = children.indexOf(thisNode);
if (index == -1) {
System.out.println("数据异常");
} else if (index == 0) {
// index==0,说明thisNode在列表中最小,当前client获得锁
return;
} else {
// 获得排名比currentNode前一位的节点
this.waitPath = "/" + rootNode + "/" + children.get(index - 1);
// 在waitPath上注册监听器,当waitPath被删除时,zookeeper会回调监听器的process方法
zk.getData(waitPath,true,new Stat());
// 进入等待锁状态
waitLatch.await();
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 解锁方法
public void zkUnlock(){
try {
zk.delete(this.currentNode,-1);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}
}
2) 分布式锁测试
(1)创建两个线程
package com.gk.case2;
import org.apache.zookeeper.KeeperException;
import java.io.IOException;
/**
* create with IntelliJ IDEA
*
* @Project :zookeeper
* @Package :com.gk.case2
* @ClassName :
* @CreateTime :2022/4/129:59
* @Version :1.0
* @Author :锦林
* @Email :[email protected]
**/
public class DistributedLockTest {
public static void main(String[] args) throws InterruptedException, IOException, KeeperException {
// 创建分布式锁 1
final DistributedLock lock1 = new DistributedLock();
// 创建分布式锁 2
final DistributedLock lock2 = new DistributedLock();
new Thread(new Runnable() {
public void run() {
try {
// 获取锁对象
lock1.zkLock();
System.out.println("线程1获取锁");
Thread.sleep(5 * 1000);
lock1.zkUnlock();
System.out.println("线程1释放锁");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
// 获取锁对象
lock2.zkLock();
System.out.println("线程2获取锁");
Thread.sleep(5 * 1000);
lock2.zkUnlock();
System.out.println("线程2释放锁");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
(2)观察控制台变化:
1)原生的 Java API 开发存在的问题
(1)会话连接是异步的,需要自己去处理。比如使用 CountDownLatch
(2)Watch 需要重复注册,不然就不能生效
(3)开发的复杂性还是比较高的
(4)不支持多节点删除和创建。需要自己去递归
2)Curator 是一个专门解决分布式锁的框架,解决了原生Java API 开发分布式遇到的问题。
详情请查看官方文档:https://curator.apache.org/index.html
3 )Curator 案例实操
(1)添加依赖
org.apache.curator
curator-framework
4.3.0
org.apache.curator
curator-recipes
4.3.0
org.apache.curator
curator-client
4.3.0
(2)代码实现
package com.gk.case3;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
/**
* create with IntelliJ IDEA
*
* @Project :zookeeper
* @Package :com.gk.case3
* @ClassName :
* @CreateTime :2022/4/1210:41
* @Version :1.0
* @Author :锦林
* @Email :[email protected]
**/
public class CuratorLockTest {
private String rootNode = "/locks";
private String connectString = "hadoop102:2181,hadoop103:2181,hadoop103:2181";
// connection超时时间
private int connectionTimeout = 2000;
// session超时时间
private int sessionTimeout = 2000;
public static void main(String[] args) {
new CuratorLockTest().test();
}
// 测试
public void test() {
// 创建分布式锁1
final InterProcessMutex lock1 = new InterProcessMutex(getCuratorFramework(), rootNode);
// 创建分布式锁1
final InterProcessMutex lock2 = new InterProcessMutex(getCuratorFramework(), rootNode);
new Thread(new Runnable() {
public void run() {
try {
// 获取锁对象
lock1.acquire();
System.out.println("线程1 获取锁");
// 测试锁重入
lock1.acquire();
System.out.println("线程1 再次获取锁");
Thread.sleep(5 * 1000);
lock1.release();
System.out.println("线程1 释放锁");
lock1.release();
System.out.println("线程1 再次释放锁");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
// 获取锁对象
lock2.acquire();
System.out.println("线程2 获取锁");
// 测试锁重入
lock2.acquire();
System.out.println("线程2 再次获取锁");
Thread.sleep(5 * 1000);
lock2.release();
System.out.println("线程2 释放锁");
lock2.release();
System.out.println("线程2 再次释放锁");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
// 分布式锁初始化
private CuratorFramework getCuratorFramework() {
// 重试策略,初试时间3秒,重试3次
ExponentialBackoffRetry policy = new ExponentialBackoffRetry(3000, 3);
// 通过工厂创建Curator
CuratorFramework client = CuratorFrameworkFactory.builder()
.connectString(connectString)
.connectionTimeoutMs(connectionTimeout)
.sessionTimeoutMs(sessionTimeout)
.retryPolicy(policy).build();
//开启连接
client.start();
System.out.println("zookeeper 初始化完成。。。");
return client;
}
}
(2)观察控制台变化: