开源客户端

ZkClient

        <dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.10</version>
</dependency>
package com.xh.zk.zkclient;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient; /**
* Created by root on 4/3/18.
*/
public class ZkClientTest {
static String conllection = "192.168.2.192:2181";
static ZkClient zkClient; public static void main(String[] args) throws InterruptedException {
zkClient = new ZkClient(conllection, 5000);
zkClient.readData("/aaa");
zkClient.readData("/aaa/bbb");
zkClient.subscribeDataChanges("/aaa", new IZkDataListener() {
public void handleDataChange(String s, Object o) throws Exception {
System.out.println("handleDataChange>>>" + s + ":" + o);
} public void handleDataDeleted(String s) throws Exception {
System.out.println("handleDataDeleted>>>" + s);
}
}); zkClient.subscribeDataChanges("/aaa/bbb", new IZkDataListener() {
public void handleDataChange(String s, Object o) throws Exception {
System.out.println("handleDataChange>>>" + s + ":" + o);
} public void handleDataDeleted(String s) throws Exception {
System.out.println("handleDataDeleted>>>" + s);
}
}); zkClient.createPersistent("/aaa/bbb", true);
zkClient.writeData("/aaa", "hello");
zkClient.writeData("/aaa/bbb", "ssss");
zkClient.deleteRecursive("/aaa");
Thread.sleep(Integer.MAX_VALUE);
}
}

结果:

handleDataChange>>>/aaa:hello
handleDataChange>>>/aaa/bbb:ssss
handleDataDeleted>>>/aaa/bbb
handleDataDeleted>>>/aaa

Curato

创建客户端

        <dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.0.0</version>
</dependency>
public class ZkCurator {

    public static void main(String[] args) throws InterruptedException {
String connectStr = "192.168.2.192:2181";
int sessionTimeOut = 5000;
int connectTimeOut = 5000;
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient(connectStr, sessionTimeOut,
connectTimeOut, retryPolicy); CuratorFramework client2 = CuratorFrameworkFactory.builder().connectString(connectStr)
.sessionTimeoutMs(sessionTimeOut).connectionTimeoutMs(connectTimeOut)
.retryPolicy(retryPolicy).build();
client.start();
client2.start(); Thread.sleep(Integer.MAX_VALUE);
} }

节点操作


/**
* C
*/
client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL)
.forPath(path, "init".getBytes());
/**
* R
*/
Stat stat = new Stat();
byte[] bytes = client.getData().storingStatIn(stat).forPath("/zk_book/hello");
System.out.println(new String(bytes));
/**
* U
*/
client.setData().withVersion(-1).forPath("/zk_book", "hi".getBytes());
System.out.println(new String(client.getData().forPath("/zk_book")));
/**
* D
*/
client.delete().deletingChildrenIfNeeded().withVersion(-1).forPath("/zk_book");

异步操作

    public static void main(String[] args) throws Exception {
String connectStr = "192.168.2.192:2181";
int sessionTimeOut = 5000;
int connectTimeOut = 5000;
String path = "/zk_book";
final CountDownLatch semaphore = new CountDownLatch(2);
ExecutorService tp = Executors.newFixedThreadPool(5); RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.builder().connectString(connectStr)
.sessionTimeoutMs(sessionTimeOut).connectionTimeoutMs(connectTimeOut)
.retryPolicy(retryPolicy).build(); client.start(); client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL)
.inBackground(new BackgroundCallback() {
public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
System.out.println("event_code:" + curatorEvent.getResultCode() + " event_type:" + curatorEvent.getType());
System.out.println("thread_result:" + Thread.currentThread().getName());
semaphore.countDown();
}
}, tp).forPath(path, "init".getBytes()); client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL)
.inBackground(new BackgroundCallback() {
public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
System.out.println("event_code:" + curatorEvent.getResultCode() + " event_type:" + curatorEvent.getType());
System.out.println("thread_result:" + Thread.currentThread().getName());
semaphore.countDown();
}
}, tp).forPath(path, "init".getBytes()); semaphore.await();
tp.shutdown(); }

结果:

event_code:0  event_type:CREATE
thread_result:pool-1-thread-1
event_code:-110 event_type:CREATE
thread_result:pool-1-thread-2

典型应用

        <dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.0.0</version>
</dependency>

事件监听

NodeCache

    public static void main(String[] args) throws Exception {
String connectStr = "192.168.2.192:2181";
int sessionTimeOut = 5000;
int connectTimeOut = 5000;
String path = "/zk_book";
final CountDownLatch semaphore = new CountDownLatch(2);
ExecutorService tp = Executors.newFixedThreadPool(5); RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.builder().connectString(connectStr)
.sessionTimeoutMs(sessionTimeOut).connectionTimeoutMs(connectTimeOut)
.retryPolicy(retryPolicy).build(); client.start(); final NodeCache nodeCache = new NodeCache(client, path, false);
nodeCache.start(true);
nodeCache.getListenable().addListener(new NodeCacheListener() {
public void nodeChanged() throws Exception {
System.out.println("data changed:" + new String(nodeCache.getCurrentData().getData()));
}
}); client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, "init".getBytes());
client.setData().forPath(path, "update".getBytes());
Thread.sleep(1000);
client.delete().forPath(path); Thread.sleep(Integer.MAX_VALUE); }

结果:

data changed:init
data changed:update

其监听的结果在创建和修改时会通知,删除时不会

Mast选举

    public static void main(String[] args) throws Exception {
String connectStr = "192.168.2.192:2181";
int sessionTimeOut = 5000;
int connectTimeOut = 5000;
String master_path = "/zk_book"; RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.builder().connectString(connectStr)
.sessionTimeoutMs(sessionTimeOut).connectionTimeoutMs(connectTimeOut)
.retryPolicy(retryPolicy).build(); client.start(); LeaderSelector selector = new LeaderSelector(client, master_path, new LeaderSelectorListenerAdapter() {
public void takeLeadership(CuratorFramework curatorFramework) throws Exception {
System.out.println("be Master");
Thread.sleep(1000);
System.out.println("give up be Master");
}
}); selector.autoRequeue();
selector.start(); Thread.sleep(Integer.MAX_VALUE); }

分布式锁

一个订单号生成器的例子

1、没有锁:

    public static void main(String[] args) {
final CountDownLatch semaphore = new CountDownLatch(1); for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
public void run() {
try {
semaphore.await();
} catch (Exception e) {
e.printStackTrace();
} SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss|SSS");
String orderNo = dateFormat.format(new Date());
System.out.println("NO:" + orderNo);
}
}).start();
}
semaphore.countDown();
}

结果:

NO:15:05:28|362
NO:15:05:28|364
NO:15:05:28|364
NO:15:05:28|363
NO:15:05:28|364
NO:15:05:28|365
NO:15:05:28|364
NO:15:05:28|365
NO:15:05:28|365
NO:15:05:28|365

2、zk分布式锁

public class ZkCurator {
public static void main(String[] args) throws Exception {
String connectStr = "192.168.2.192:2181";
int sessionTimeOut = 5000;
int connectTimeOut = 5000;
String lock_path = "/zk_lock"; RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.builder().connectString(connectStr)
.sessionTimeoutMs(sessionTimeOut).connectionTimeoutMs(connectTimeOut)
.retryPolicy(retryPolicy).build();
client.start(); final InterProcessMutex lock = new InterProcessMutex(client, lock_path);
final CountDownLatch semaphoer = new CountDownLatch(1); for (int i = 0; i < 30; i++) {
new Thread(new Runnable() {
public void run() {
try {
semaphoer.await();
lock.acquire();
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
} SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss|SSS");
String orderNo = dateFormat.format(new Date());
System.out.println("NO:" + orderNo);
try {
lock.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
semaphoer.countDown();
} }

结果:

NO:15:26:49|695
NO:15:26:50|706
NO:15:26:51|715
NO:15:26:52|733
NO:15:26:53|753
...

Zookeeper学习笔记4的更多相关文章

  1. ZooKeeper 学习笔记

    ZooKeeper学习笔记 1.   zookeeper基本概念 zookeeper是一个分布式的,开放源码的分布式应用程序协调服务,是hadoop和Habase的重要组件,是为分布式应用提供一致性服 ...

  2. ZooKeeper学习笔记(二)——内部原理

    zookeeper学习笔记(二)--内部原理 1. zookeeper的节点的类型 总的来说可以分为持久型和短暂型,主要区别如下: 持久:客户端与服务器端断开连接的以后,创建的节点不会被删除: 持久化 ...

  3. ZooKeeper学习笔记(一)——概述

    zookeeper学习笔记(一)--概述 1. 概述 Zookeeper是一个开源的分布式的,为分布式应用提供协调服务的Apache项目.zookeeper从设计模式的角度来理解:是一个基于观察者设计 ...

  4. Zookeeper学习笔记(中)

    Zookeeper学习笔记(中) Zookeeper的基本原理和基本实现 深入了解ZK的基本原理 ZK的一致性: ZAB 协议: Zookeeper 原子消息广播协议 ZK通过选举保证 leader ...

  5. Zookeeper学习笔记(上)

    Zookeeper学习笔记 本篇主要是一些基本的介绍和API的使用介绍, 有些只是记录了知识点,而没有完全在笔记中详细解释, 需要自行查找资料补充相关概念 主要参考了课程中的内容: Zookeeper ...

  6. ZooKeeper学习笔记一:集群搭建

    作者:Grey 原文地址:ZooKeeper学习笔记一:集群搭建 说明 单机版的zk安装和运行参考:https://zookeeper.apache.org/doc/r3.6.3/zookeeperS ...

  7. ZooKeeper学习笔记三:使用ZooKeeper实现一个简单的配置中心

    作者:Grey 原文地址:ZooKeeper学习笔记三:使用ZooKeeper实现一个简单的配置中心 前置知识 完成ZooKeeper集群搭建以及熟悉ZooKeeperAPI基本使用 需求 很多程序往 ...

  8. ZooKeeper学习笔记二:API基本使用

    Grey ZooKeeper学习笔记二:API基本使用 准备工作 搭建一个zk集群,参考ZooKeeper学习笔记一:集群搭建. 确保项目可以访问集群的每个节点 新建一个基于jdk1.8的maven项 ...

  9. ZooKeeper学习笔记四:使用ZooKeeper实现一个简单的分布式锁

    作者:Grey 原文地址: ZooKeeper学习笔记四:使用ZooKeeper实现一个简单的分布式锁 前置知识 完成ZooKeeper集群搭建以及熟悉ZooKeeperAPI基本使用 需求 当多个进 ...

  10. Zookeeper学习笔记(下)

    这是ZK学习笔记的下篇, 主要希望可以分享一些 ZK 的应用以及其应用原理 我本人的学习告一段落, 不过还遗留了一些ZK相关的任务开发和性能测试的任务, 留待以后完成之后再通过其他文章来进行分享了 Z ...

随机推荐

  1. M1-Flask-Day1

    前情概要 1.flask的基本使用 - 配置 - 路由 - 视图 - 请求与响应相关 - 模板 2.flask基于装饰器实现的路由 - 基本操作 - functools - 带参数的装饰器 - 源码剖 ...

  2. mysql全备份脚本速查

    mysql全备份脚本 # 快捷备份方式[root@nb scripts]# cat db.backup.sh #!/bin/bashmysqldump -ubackup -pbackuppwd -P3 ...

  3. Spring_xml和注解混合方式开发

    1. spring核心配置文件: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=&q ...

  4. C++回顾day02---<拷贝构造函数:重点>

    一:补充---无参构造函数(默认无参构造函数)在实例化对象时注意点 (一)若没有写构造函数,则类会含有一个默认无参构造函数 (二)若自定义一个构造函数,则类不会提供默认构造函数 class A { p ...

  5. python数据结构总结

    一.列表 1.列表脚本操作符: (1)扩增的操作符: “+”:用于组合列表:如[1,2,3]+[4,5,6]==>[1,2,3,4,5,6] "*":重复;如[2,3]*2= ...

  6. vue表单校验提交报错TypeError: Cannot read property 'validate' of undefined

    TypeError: Cannot read property 'validate' of undefined at VueComponent.submitForm (plat_users.html: ...

  7. springBoot整合mybatis、jsp 或 HTML

    springBoot整合mybatis.jsp Spring Boot的主要优点: 1:  为所有Spring开发者更快的入门: 2:  开箱即用,提供各种默认配置来简化项目配置: 3:  内嵌式容器 ...

  8. java基础之反射---重要

    java反射: 反射是框架设计的灵魂 (使用的前提条件:必须先得到代表的字节码的Class,Class类用于表示.class文件(字节码)):   1:获取Class字节码文件对象的三种方式: /** ...

  9. linux_添加图标

    sudo gedit /usr/share/applications/Pycharm.desktop [Desktop Entry] Type=Application Name=Pycharm Gen ...

  10. tomcat下的Cookie特殊符号问题

    案例:在项目中通过Cookie方式临时存放检索条件,不小心在Cookie值中使用了特殊符号"@",导致在服务器端无法正确解析Cookie值.之所以说"不小心", ...