开源客户端

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. (线段判交的一些注意。。。)nyoj 1016-德莱联盟

    1016-德莱联盟 内存限制:64MB 时间限制:1000ms 特判: No通过数:9 提交数:9 难度:1 题目描述: 欢迎来到德莱联盟.... 德莱文... 德莱文在逃跑,卡兹克在追.... 我们 ...

  2. MySQL mysqldump 导入/导出 结构&数据&存储过程&函数&事件&触发器

    ———————————————-库操作———————————————-1.①导出一个库结构 mysqldump -d dbname -u root -p > xxx.sql ②导出多个库结构 m ...

  3. 这3周以来的面试总结(C#/.net 智能硬件/物联网)

    2017.3找工作面试记录-第一周 2017.3找工作面试记录-第一周(2) 2017.3找工作面试记录-第二周 2017.4找工作面试记录-第三周 2017.4找工作面试记录-第三周(2)--金蝶 ...

  4. (转载) python3: beautifulsoup的使用

    转载: https://www.cnblogs.com/chimeiwangliang/p/8649003.htmlfrom bs4 import BeautifulSoup import reque ...

  5. Linux truncate的使用方法介绍

    Linux truncate的使用方法介绍 参考资料:https://www.fengbohello.top/archives/linux-truncate 本命令缩减或扩充指定文件的大小为指定值.参 ...

  6. linux下安装SlickEdit

    title: linux下安装SlickEdit tags: 软件 date: 2018-10-08 21:32:12 --- linux下安装SlickEdit 下载安装包和补丁文件 补丁文件 官方 ...

  7. GO 中输出打印的常用函数

    1.Println 可以打印字符串和变量(任何类型)    println函数在输出后自动增加一个换行 例: a:=10 b:=“string” fmt.Println(a)  //right fmt ...

  8. centos 7.2 部署并升级gitlab

    事由: 老git服务器centos 7.2上的git版本是8.13.5,先特在一台测试机centos 7.2上安装git 8.13.5 后,还原git后,在对测试服务器上git进行升级操作. 测试服务 ...

  9. java io系列20之 PipedReader和PipedWriter

    本章,我们学习PipedReader和PipedWriter.它们和“PipedInputStream和PipedOutputStream”一样,都可以用于管道通信. PipedWriter 是字符管 ...

  10. HDU 6375(双端队列 ~)

    题意是有至多150000个双端队列,400000次简单操作,直接开会导致内存超限,所以用 STL 中的 map 和 deque ,而读入过大已经在题目中有所说明,直接用已经给出的快速读入即可.要注意的 ...