添加依赖

<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. Cobbler 部署

    环境介绍 Cobbler 操作系统: Centos-7.2-x86_64 Cobbler服务器地址: 10.90.0.10 部署 Cobbler 安装 Centos epel 原 [root@node ...

  2. Android实现QQ登录

    https://www.jianshu.com/p/e59bc198e88f

  3. cmd 安装第三方库问题

    pip install 包名 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com 一定要指定 信任豆瓣源,不然就算换了源 ...

  4. Python Tuple(元组) max()方法

    描述 Python 元组 max() 函数返回元组中元素最大值.高佣联盟 www.cgewang.com 语法 max()方法语法: max(tuple) 参数 tuple -- 指定的元组. 返回值 ...

  5. Pintech品致—示波器探头技术标准倡导者

     Pintech品致是仪器仪表的品牌,全球示波器探头第一品牌,示波器探头技术标准倡导者:“两点浮动”电压测试创始人:世界知名品牌,泰克(Tektronix),罗德与施瓦茨R&S,是德(Keys ...

  6. HA模式下的java api访问要点

    在非HA架构的HDFS中,客户端要通过java接口调用HDFS时一般是在JobRunner的类中按照下面的方式: 因为nodename只有一个节点所以会在代码中显式的指明要连接哪一个节点:但是在HA模 ...

  7. SqlServer 查询的几种方式以及数字函数、时间函数的应用总结(回归基础)

    --语法:select * from 表名 *表示查询所有字段数据 select * from Class select * from Student select * from RankingLis ...

  8. 新鲜整理的Java学习大礼包!!锵锵锵锵~

    第一部分:Java视频资源! 前端 HTML5新元素之Canvas详解 https://www.bilibili.com/video/BV1TE41177TE HTML5之WebStorage详解 h ...

  9. python1.1列表知识点:

    #定义列表[]a=[1,2,3,4,5,6,7,"hello","world"]#列表索引从0开始,指定位置提取元素print(a[3])print(a) #列 ...

  10. “随手记”开发记录day05

    今天完成了关于统计页面里面的总览页面 里面的功能有可以显示你这个月的花费最多的账单,和收入最多的页面 还有总计 运行效果如图所示