一、Linux单机安装Zookeeper
首先我们下载zookeeper官网下载即可 我的3.5.6版本 (自取) 只想看springboot集成的同学略过直接看二
链接:https://pan.baidu.com/s/1HnBsSz_AP6P_vEIqe5wlBQ
提取码:qzsv
-
上传至Linux服务器 使用命令 tar -zxvf 包名 进行解压
-
进入文件夹 首先我们将配置文件拷贝一份 进入conf目录下 cp zoo_sample.cfg zoo.cfg
-
编辑zoo.cfg 配置文件 vi zoo.cfg 开放端口 设置dataDir与dataLogDir两个文件存储路径 然后保存退出
-
输入 bin/zkServer.sh start 启动zookeeper
-
启动完成后输入 jps可查看进程是否存在
-
输入bin/zkCli.sh 即可进入zookeeper
这里我们可以输入 一些简单操作命令 进行操作 详细内容可以网上搜索这里不一一介绍 (操作如下图所示)
ls / //查看根目录所有节点
create /testNode 我是测试内容 //create创建节点
get /testNode //获取节点信息
set /testNode 我是更新后的测试数据
二、Springboot集成操作节点增删改查
直接上代码
//pom依赖
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
//appication.properties 配置文件
# 项目配置端口
server.port=9809
# zookeeper ip 端口
zookeeper.address=ip:2181
#连接超时
zookeeper.address.timeout=4000
configuration配置类 代码是直接可以跑的 跑不通的同学就是引入依赖问题 可以仔细查看import
//configuration 配置类
import com.example.demoalgorithm.controller.ZookeeperTest;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.CountDownLatch;
@Configuration
public class ZookeeperConfig {
@Value("${zookeeper.address}")
private String connectString;
@Value(("${zookeeper.address.timeout}"))
private int timeout;
@Bean(name = "zkClient")
public ZooKeeper zkClient(){
ZooKeeper zooKeeper=null;
try {
final CountDownLatch countDownLatch = new CountDownLatch(1);
zooKeeper = new ZooKeeper(connectString, timeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
if(Event.KeeperState.SyncConnected==event.getState()){
countDownLatch.countDown();
}
}
});
countDownLatch.await();
System.out.println(zooKeeper.getState()+"ZooKeeper状态");
logger.info("ZooKeeper连接状态={}",zooKeeper.getState());
}catch (Exception e){
logger.error("初始化ZooKeeper异常={}",e);
}
return zooKeeper;
}
}
添加完配置代理类直接进行zookeeper连接测试
import com.example.demoalgorithm.config.ZkApi;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import static org.apache.zookeeper.ZooDefs.OpCode.exists;
@RestController
public class ZookeeperTest {
private static final Logger logger = LoggerFactory.getLogger(ZookeeperTest.class);
@Autowired
private ZooKeeper zkClient;
// 查询节点是否存在 参数:节点路径 例如 /testNode
@GetMapping("selectNode")
public void selectNode(String path){
try {
logger.info("[开始查询节点Stat]");
Stat exists = zkClient.exists(path, true);
logger.info("[查询成功]",exists.getVersion());
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//查询节点数据 此方法返回节点内数据 参数:节点路径 例如 /testNode
@GetMapping("queryData")
public String queryData(String nodePath) throws KeeperException, InterruptedException{
Stat stat = zkClient.exists(nodePath, false);
logger.info("准备查询节点Stat,path:{}",nodePath);
//data 为节点内数据
String data = new String(zkClient.getData(nodePath, false, stat));
logger.info("结束查询节点Stat,data:{}", data);
return data;
}
//此方法为创建节点 参数:节点路径 节点数据 例如:/testNode 测试数据
@GetMapping("/createNode")
public void create(String nodePath,String nodeData) throws KeeperException, InterruptedException{
logger.info("开始创建节点:{},数据:{}",nodePath,nodeData);
List<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;
CreateMode createMode = CreateMode.PERSISTENT;
// result 节点名
String result = zkClient.create(nodePath, nodeData.getBytes(), acl, createMode);
logger.info("创建节点返回结果:{}",result);
logger.info("完成创建节点:{}, 数据:{}",nodePath,nodeData);
}
// 修改接口
@GetMapping("updateNode")
public Stat update(String nodePath,String nodeData) throws KeeperException, InterruptedException{
Stat stat = zkClient.exists(nodePath, false);
logger.info("准备修改节点,path:{},data:{},version:{}",nodePath,nodeData,stat.getVersion());
Stat newStat = zkClient.setData(nodePath, nodeData.getBytes(), stat.getVersion());
logger.info("修改节点完成,path:{},data:{},version:{}",nodePath,nodeData,stat.getVersion());
return stat;
}
//删除接口
@GetMapping("deleteNode")
public String delete(String nodePath) throws InterruptedException, KeeperException{
//删除节点前先查询该节点信息
Stat stat = zkClient.exists(nodePath, false);
logger.info("准备删除节点,path:{},原version:{}",nodePath, stat.getVersion());
zkClient.delete(nodePath, stat.getVersion());
logger.info("完成删除节点,path:{0}",nodePath);
return "success";
}
}