zookeeper集群搭建及分布式锁实现
1. 集群搭建
zookeeper的部署比较简单,直接下载压缩包之后直接运行即可,这里推荐docker部署,只需配置一个容器,其他拷贝这个容器即可 在部署前,你要确保你安装了docker,并安装ssh、java等相关必要的环境
docker 配置ssh远程连接
在本次实验中,我用到了3个容器,为了方便操作,我配置了免密登陆
ssh-keygen 指令生成密钥,密钥保存在 /root/.ssh 文件夹下ssh-copy-id ip地址 命令上传密钥,要确保三个容器都能互相无密码登陆
部署zookeeper
- 下载zookeeper,
wget https://downloads.apache.org/zookeeper/stable/apache-zookeeper-3.6.3-bin.tar.gz - 解压
tar -xcf apache-zookeeper-3.6.3-bin.tar.gz -C /zookeeper ,解压到/zookeeper 目录下 mv /zookeeper/apache-zookeeper-3.6.3-bin/ /zookeeper - 修改配置,进入conf目录
cd /zookeeper/conf ,复制配置文件 cp zoo-sample.conf zoo.conf ,并更改为如下内容 - 在
zoo.conf 的dataDir 目录下,新建myid 文件,不同的容器内容分别为 0 ,1 ,2,要与配置文件中的 server.* 的* 对应 - 用
scp 命令,将/zookeeper 文件夹上传到其他容器中scp -r /zookeeper/ ip:/zookeeper - 在其他容器中也新建响应的
myid 文件 - 将
/zookeeper/bin 添加到环境变量中(你也可以不配置,不过需要进入 /zookeeper/bin 才能执行zk命令) - 所有容器执行
zkServer.sh start ,运行zookeeper
现在zookeeper集群以完成部署,可以 用zkServer.sh status 查看当前zookeeper的状态
2. 分布式锁
在gradle中添加依赖 implementation 'org.apache.curator:curator-recipes:5.1.0'
实现代码如下
public static void main(String[] args) throws Exception {
Application application = new Application();
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1500, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.1.101:2181, 192.168.1.102:2181, 192.168.1.103:2181", retryPolicy);
client.start();
InterProcessMutex interProcessMutex = new InterProcessMutex(client, "/simple/lock");
while (true) {
interProcessMutex.acquire();
String path = interProcessMutex.getParticipantNodes().stream().findFirst().get();
System.out.println("process " + args[0] + " get the lock " + path.substring(path.lastIndexOf("-")));
interProcessMutex.release();
}
}
这里为了验证分布式,我们需要运行两个终端,一个终端启动参数传p1,一个终端启动参数传p2
  可以看到两个终端同时运行时,是交替获得锁的,及一个程序获得锁之后,另一个程序需要的等待锁释放才可上锁
|