开源客户端

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. 解决mysql乱码问题

    在mysql根目录下创建my.ini文件 my.ini内容为: [mysqld] # 设置默认字符集,只会影响新建数据库的默认字符集 character-set-server=utf8

  2. 运用tp5上传图片,并生成缩略图

    最近想做个相册,需要用到上传图像,并且考虑到性能问题,还要生成缩略图,就学习下.在网上看了很多大神写的文章,经过各种调试总算出来了,分享下.不好之处,多多指教 ​ ​ ps:运用tp5图片类生成缩略图 ...

  3. WiFi热点(1):windows8建wifi虚拟热点

    在windows8系统中,打开记事本,写入下面两行:@netsh wlan set hostednetwork mode=allow ssid=wuyazhe key=88888888@netsh w ...

  4. SQLMAP UDF提权

    SQLMAP UDF提权      1.连接mysql数据打开一个交互shell: sqlmap.py -d mysql://root:root@127.0.0.1:3306/test --sql-s ...

  5. Shell 同步时间脚本

    Linux系统同步时间脚本 Linux操作系统,如果时间和网络时间差距太大的话.可能会导致程序,进程启动不了.所以linux系统时间同步显得尤为重要,本文在借鉴网上众多资料后,以centos_6.X系 ...

  6. PHP 连接 Memcached 服务

    1.需要安装php的Memcached扩展,具体安装步骤不做介绍了. 2.php连接memcached的mem.php 文件 <?php $memcache = new Memcached; $ ...

  7. weblogic每天日志合并shell脚本 [个人记录]【转】【补】

    from RogerZhu modified by King sh logback.rb "/data/logs/" "/tmp/domain" "a ...

  8. javasrcipt的作用域和闭包(二)续篇之:函数内部提升机制与Variable Object

    一个先有鸡还是先有蛋的问题,先看一段代码: a = 2; var a; console.log(a); 通常我们都说JavaScript代码是由上到下一行一行执行,但实际这段代码输出的结果是2.但这段 ...

  9. 开源框架.netCore DncZeus学习(四)项目升级

    今天发现开源代码从1.0.0.1升级到了1.0.1.0,主要去掉了id主键,升级办法打开DncZeus,右键Git Bash Here,输入以下命令 合并失败,因为上一节尝试修改了几个代码,解决办法 ...

  10. Webpack2学习记录-2

    这篇在 webpack-demo 目前下新建一个 w2 目录,学习 webpack.config.js 及 与 npm scripts 的使用. 1.w2 下新建一个 webpack.config.j ...