zookeeper的java应用

zookeeper的概念

一般由多个服务器和多个客户端组成,对应操作分别为zkServerzkCli

zookeeper命令行操作

(1)服务端操作
1.启动
./zkServer.sh start

2.停止
./zkServer.sh stop


3.查看状态
./zkServer.sh status


4.重启
./zkServer.sh restart


(2)客户端操作
连接zk服务端
./zkCli.sh server localhost:2181

1.新增
create

2.删除
delete 和 rmr, rmr强制删除,del在目录下还存在目录的情况删除会失败,deleteall与rmr同,rmr在比较老的版本中使用

3.修改
set

4.查询
ls 和 ls2, ls2能查询更多模式等节点信息
get 获取数据

5.帮助
help

6.退出
quit

zookeeper的java API

三种方式:原生javaAPI、zkClient、Curator。Curator最方便,优先选择

1.坐标
	<!--zkclient-->
<dependency>
     <groupId>com.github.sgroschupf</groupId>
     <artifactId>zkclient</artifactId>
     <version>0.1</version>
</dependency>
        <!-- 引入zookeeper -->
<dependency>
   <groupId>org.apache.curator</groupId>
   <artifactId>curator-framework</artifactId>
   <version>4.0.0</version>
</dependency>
<dependency>
   <groupId>org.apache.curator</groupId>
   <artifactId>curator-recipes</artifactId>
   <version>4.0.0</version>
</dependency>
<dependency>
   <groupId>org.apache.zookeeper</groupId>
   <artifactId>zookeeper</artifactId>
   <version>3.4.14</version>
   <!--排除这个slf4j-log4j12,可能会引起日志冲突-->
   <exclusions>
       <exclusion>
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-log4j12</artifactId>
       </exclusion>
   </exclusions>
</dependency>


2.客户端连接

//1 重试策略:初试时间为1s 重试10次
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
//2 通过工厂创建连接
CuratorFramework client = CuratorFrameworkFactory.builder()
       .connectString(CONNECT_ADDR).connectionTimeoutMs(CONNECTION_TIMEOUT)
        .sessionTimeoutMs(SESSION_TIMEOUT)
        .retryPolicy(retryPolicy)
        .namespace("super") //命名空间
        .build();
       
        //3 开启连接
        cf.start();

3.新增(带模式、多级根目录)

//创建永久节点
client.create().forPath("/curator","/curator data".getBytes());
   
 //创建永久有序节点      client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/curator_sequential","/curator_sequential data".getBytes());
        
 //创建临时节点
 client.create().withMode(CreateMode.EPHEMERAL)
            .forPath("/curator/ephemeral","/curator/ephemeral data".getBytes());

//创建临时有序节点
client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL) .forPath("/curator/ephemeral_path1","/curator/ephemeral_path1 data".getBytes());         
        client.create().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/curator/ephemeral_path2","/curator/ephemeral_path2 data".getBytes());
         
//测试检查某个节点是否存在
 Stat stat1 = client.checkExists().forPath("/curator");        
 Stat stat2 = client.checkExists().forPath("/curator2");

//创建或修改多级节点
client.create().orSetData().creatingParentContainersIfNeeded()
    .forPath("/curator/del_key1","/curator/del_key1 data".getBytes());

4.删除

//删除该节点
client.delete().forPath("/curator/del_key1");
       
//级联删除子节点   guaranteed表示必须成功否则重试的删除  client.delete().guaranteed().deletingChildrenIfNeeded().forPath("/curator/del_key2");

//删除后回调
client.delete().guaranteed().inBackground(new BackgroundCallback(){
@Override
public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
    System.out.printin("我被删除了〜");
}
}).forPath("/app1");

5.修改
client.setData().forPath("/curator","/curator modified data".getBytes());
//根据版本修改
Stat stat = new Stat();
client.getData().storingStatIn(stat).forPath("/node1/data1");
int version =  stat.getVersion();
client.setData().withVersion(version).forPath("/node1/data1");

6.查询

 //获取某个节点的所有子节点
 System.out.println(client.getChildren().forPath("/"));
         
 //获取某个节点数据
 System.out.println(new String(client.getData().forPath("/curator")));

//查询状态信息
Stat stat = new Stat();
client.getData().storingStatIn(stat).forPath("/node1");


7.分布式锁

InterProcessMutex lock = new InterProcessMutex(client, lockPath);
if ( lock.acquire(maxWait, waitUnit) ) 
{
    try 
    {
        // do some work inside of the critical section here
    }
    finally
    {
        lock.release();
    }
}

8.监听器 NodeCache PathChildrenCache TreeCache
final NodeCache nodeCache = new ModeCache(client, "/appl");
//注册监听
nodeCache.getListenable().addListener(new NodeCacheLlstener(){
    @Override
    public void nodeChanged() throws Exception {
        byte[] data nodeCache.getCurrentData().getData();
    }
});
//开启监听.如果设贸为true,则开启监听是,加载缓冲数据
nodeCache.start( true);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值