添加依赖

<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.6</version>
</dependency>

注册

定义一个参数model

public class ZookeeperRegisterConnectModel {
//连接地址(可以多个地址,用逗号分割)
private String connectString;
private int sessionTimeout; public String getConnectString() {
return connectString;
} public void setConnectString(String connectString) {
this.connectString = connectString;
} public int getSessionTimeout() {
return sessionTimeout;
} public void setSessionTimeout(int sessionTimeout) {
this.sessionTimeout = sessionTimeout;
} public ZookeeperRegisterConnectModel(){}
public ZookeeperRegisterConnectModel(String connectString, int sessionTimeout) {
this.connectString = connectString;
this.sessionTimeout = sessionTimeout;
}
}

服务注册具体代码:

public class ZookeeperRegisterNodeServiceImpl implements IRegisterNodeService, Closeable {

    private ZooKeeper zk;

    /**
* 实例连接zookeeper
*
* @param zookeeperConnectModel
* @throws IOException
*/
public ZookeeperRegisterNodeServiceImpl(ZookeeperRegisterConnectModel zookeeperConnectModel) throws IOException {
//创建一个与ZooKeeper服务器的连接
zk = new ZooKeeper(zookeeperConnectModel.getConnectString(), zookeeperConnectModel.getSessionTimeout(), new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) { }
});
} /**
* 创建节点
*
* @param service 服务接口名称
* @param address 服务发布的地址和端口
* @return
* @throws KeeperException
* @throws InterruptedException
*/
public String createNode(String service, String address) throws KeeperException, InterruptedException {
Stat stat = zk.exists("/" + service, false);
//不存在就创建根节点
if (stat == null) {
zk.create("/" + service, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
//创建一个子节点
return zk.create("/" + service + "/" + address, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
} @Override
public void close() {
try {
zk.close();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

发现

服务发现具体代码:

public class ZookeeperGetChildrenServiceImpl implements IGetChildrenService , Closeable {

    private ZooKeeper zk;

    public ZookeeperGetChildrenServiceImpl(ZookeeperFindConnectModel zookeeperConnectModel) throws IOException {
//创建一个与ZooKeeper服务器的连接
zk = new ZooKeeper(zookeeperConnectModel.getConnectString(), zookeeperConnectModel.getSessionTimeout(), new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) { }
});
} /**
* 获取路径下所有节点,幷随机返回一个节点的信息
* @param path
* @return
* @throws KeeperException
* @throws InterruptedException
*/
@Override
public String getChildren(String path) throws KeeperException, InterruptedException {
List<String> childrens = zk.getChildren("/"+path, false);
if(null==childrens ||childrens.size()==0){
return null;
}
// shuffle 打乱顺序
Collections.shuffle(childrens);
return childrens.get(0);
} @Override
public void close() {
try {
zk.close();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

测试

public class RegisterFindTest {
private String service = "zookeeperTest";
boolean error=false; @Test
public void findTest() throws InterruptedException, IOException, KeeperException {
registerTest(); IGetChildrenService getChildrenService = new ZookeeperGetChildrenServiceImpl(new ZookeeperFindConnectModel("192.168.10.200:2181", 5000));
List<Thread> threads=new ArrayList<>();
for(int i=0;i<500;i++){
Thread thread = new Thread() {
@Override
public void run() {
try { String organization = getChildrenService.getChildren(service);
Assert.assertNotNull(service + "服务地址没有找到", organization);
} catch (InterruptedException | KeeperException |AssertionError e) {
error=true;
}
}
};
thread.start();
threads.add(thread);
}
threads.forEach(thread -> {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Assert.assertFalse(error);
} private void registerTest() throws IOException, KeeperException, InterruptedException {
IRegisterNodeService registerNodeService = new ZookeeperRegisterNodeServiceImpl(new ZookeeperRegisterConnectModel("192.168.10.200:2181", 18000));
registerNodeService.createNode(service, "192.168.10.11:1111");
registerNodeService.createNode(service, "192.168.10.22:2222");
registerNodeService.createNode(service, "192.168.10.33:3333");
}
}

其他基本操作

    /**
** 获取节点上面的数据
** @param path 路径
** @return
** @throws KeeperException
** @throws InterruptedException
*
*/
public String getData(String path) throws KeeperException, InterruptedException {
byte[] data = zookeeper.getData(path, false, null);
if (data == null) {
return "";
}
return new String(data);
} /**
* 设置节点信息
* @param path 路径
* @param data 数据
* @return
* @throws KeeperException
* @throws InterruptedException
*/
public Stat setData(String path,String data) throws KeeperException,InterruptedException{
Stat stat = zookeeper.setData(path, data.getBytes(), -1);
return stat;
} /**
* 删除节点
* @param path
* @throws InterruptedException
* @throws KeeperException
*/
public void deleteNode(String path) throws InterruptedException, KeeperException{
zookeeper.delete(path, -1);
} /**
* 获取创建时间
* @param path
* @return
* @throws KeeperException
* @throws InterruptedException
*/
public String getCTime(String path) throws KeeperException, InterruptedException{
Stat stat = zookeeper.exists(path, false);
return String.valueOf(stat.getCtime());
} /**
* 获取某个路径下孩子的数量
* @param path
* @return
* @throws KeeperException
* @throws InterruptedException
*/
public Integer getChildrenNum(String path) throws KeeperException, InterruptedException{
int childenNum = zookeeper.getChildren(path, false).size();
return childenNum;
} /**
* 关闭连接
* @throws InterruptedException
*/
public void closeConnection() throws InterruptedException{
if (zookeeper != null) {
zookeeper.close();
}
}

zookeeper简单实现注册与发现以及其他基本操作的更多相关文章

  1. 【转帖】基于Zookeeper的服务注册与发现

    http://www.techweb.com.cn/network/hardware/2015-12-25/2246973.shtml 背景 大多数系统都是从一个单一系统开始起步的,随着公司业务的快速 ...

  2. Web Api 基于Zookeeper的服务注册与发现

    安装与差异 Zookeeper安装请参考我上篇文章 http://www.cnblogs.com/woxpp/p/7700368.html 基于Nginx的服务提供和消费 基于zookeeper的服务 ...

  3. SpringCloud用Zookeeper做服务注册与发现中心代码实现

    一:Zookeeper用的是3.5.5版本,SpringBoot用的是2.1.6版本,SpringCloud用的是Greenwich.SR2版本,JDK用的是1.8: 服务提供者product-ser ...

  4. 基于ZooKeeper实现简单的服务注册于发现

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/Shaun_luotao/article/ ...

  5. Zookeeper服务注册与发现原理浅析

    了解Zookeeper的我们都知道,Zookeeper是一种分布式协调服务,在分布式应用中,主要用来实现分布式服务的注册与发现以及分布式锁,本文我们简单介绍一下Zookeeper是如何实现服务的注册与 ...

  6. Zookeeper实现服务注册/发现

    what that? Zookeeper在分布式开发中使用频繁,但许多框架都对其进行了封装,初学者可能无法较好的理解其工作原理,该文章演示了使用Zookeeper实现服务注册,服务发现的简单demo, ...

  7. springcloud之服务注册与发现(zookeeper注册中心)-Finchley.SR2版

    新年第一篇博文,接着和大家分享springcloud相关内容:本次主要内容是使用cloud结合zookeeper作为注册中心来搭建服务调用,前面几篇文章有涉及到另外的eureka作为注册中心,有兴趣的 ...

  8. 史上最简单的 SpringCloud 教程 | 第一篇: 服务的注册与发现(Eureka)

    一.spring cloud简介 spring cloud 为开发人员提供了快速构建分布式系统的一些工具,包括配置管理.服务发现.断路器.路由.微代理.事件总线.全局锁.决策竞选.分布式会话等等.它运 ...

  9. (转) 史上最简单的 SpringCloud 教程 | 第一篇: 服务的注册与发现(Eureka)

    一.spring cloud简介 spring cloud 为开发人员提供了快速构建分布式系统的一些工具,包括配置管理.服务发现.断路器.路由.微代理.事件总线.全局锁.决策竞选.分布式会话等等.它运 ...

随机推荐

  1. bootstrap-treeview 研究一下

    一直以来都是拿来主义,现在正好有空,也正好用到,准备好好研究下bootstrap-treeview. 实现目标:可搜索,可复选选中的权限控制菜单项. 研究失败 转 jstree

  2. clion 如何执行外部文件

    https://blog.csdn.net/he_yang_/article/details/96644480 这里这里

  3. Spring学习之——手写Mini版Spring源码

    前言 Sping的生态圈已经非常大了,很多时候对Spring的理解都是在会用的阶段,想要理解其设计思想却无从下手.前些天看了某某学院的关于Spring学习的相关视频,有几篇讲到手写Spring源码,感 ...

  4. Python while 循环中使用 else 语句

    Python while 循环中使用 else 语句: else:表示 while 中的语句正常执行完,然后执行 else 语句的部分. 示例: # while 判断条件: # 一行语句 或 多行语句 ...

  5. jieba尝鲜

    import jieba strings = '我工作在安徽的安徽师范大学,这个大学很美丽,在芜湖' # print(dir(jieba)) dic_strings = {} lst_strings ...

  6. PHP is_readable() 函数

    定义和用法 is_readable() 函数检查指定的文件是否可读. 如果文件可读,该函数返回 TRUE. 语法 is_readable(file) 参数 描述 file 必需.规定要检查的文件. 提 ...

  7. day3. 六大标准数据类型的类型转换

    一.强制类型转换Number 1.int  强制转换成整型 var1 = 13 var2 = 13.789 var3 = True var4 = 5-7j var5 = "" va ...

  8. day22:面向对象封装对象操作&类操作&面向对象删除操作

    面向对象程序开发 1.类的三种定义方式 class MyClass: pass class MyClass(): #(推荐) pass class MyClass(object): # object类 ...

  9. Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:testCompile (default-testCompile) on project docker_springcloud_demo: Fatal error compiling: 无效的标记: -parameters -> [Help 1]

    [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:testCompile (def ...

  10. 如何打印完整的MYSQL带参数SQL日志信息

    在mysql的jdbc中开启sql分析,如下: jdbc.url=jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=U ...