首页 > 其他分享 >Watch监听-示例

Watch监听-示例

时间:2023-04-24 16:27:32浏览次数:30  
标签:示例 Watch new public client org apache import 监听

package com.hw.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class CuratorWatcherTest {


    private CuratorFramework client;

    /**
     * 建立连接
     */
    @Before
    public void testConnect() {

        /*
         *
         * @param connectString       连接字符串。zk server 地址和端口 "127.0.0.1:2181,127.0.0.1:2181"
         * @param sessionTimeoutMs    会话超时时间 单位ms
         * @param connectionTimeoutMs 连接超时时间 单位ms
         * @param retryPolicy         重试策略
         */
       /* //重试策略
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000,10);
        //1.第一种方式
        CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181",
                60 * 1000, 15 * 1000, retryPolicy);*/
        //重试策略
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 10);
        //2.第二种方式
        //CuratorFrameworkFactory.builder();
        client = CuratorFrameworkFactory.builder()
                .connectString("192.168.149.135:2181")
                .sessionTimeoutMs(60 * 1000)
                .connectionTimeoutMs(15 * 1000)
                .retryPolicy(retryPolicy)
                .namespace("hw")
                .build();

        //开启连接
        client.start();

    }

    @After
    public void close() {
        if (client != null) {
            client.close();
        }
    }

    /**
     * 演示 NodeCache:给指定一个节点注册监听器
     */

    @Test
    public void testNodeCache() throws Exception {
        //1. 创建NodeCache对象
        final NodeCache nodeCache = new NodeCache(client,"/app1");
        //2. 注册监听
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                System.out.println("节点变化了~");

                //获取修改节点后的数据
                byte[] data = nodeCache.getCurrentData().getData();
                System.out.println(new String(data));
            }
        });

        //3. 开启监听.如果设置为true,则开启监听是,加载缓冲数据
        nodeCache.start(true);


        while (true){

        }
    }



    /**
     * 演示 PathChildrenCache:监听某个节点的所有子节点们
     */

    @Test
    public void testPathChildrenCache() throws Exception {
        //1.创建监听对象
        PathChildrenCache pathChildrenCache = new PathChildrenCache(client,"/app2",true);

        //2. 绑定监听器
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                System.out.println("子节点变化了~");
                System.out.println(event);
                //监听子节点的数据变更,并且拿到变更后的数据
                //1.获取类型
                PathChildrenCacheEvent.Type type = event.getType();
                //2.判断类型是否是update
                if(type.equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)){
                    System.out.println("数据变了!!!");
                    byte[] data = event.getData().getData();
                    System.out.println(new String(data));

                }
            }
        });
        //3. 开启
        pathChildrenCache.start();

        while (true){

        }
    }





    /**
     * 演示 TreeCache:监听某个节点自己和所有子节点们
     */

    @Test
    public void testTreeCache() throws Exception {
        //1. 创建监听器
        TreeCache treeCache = new TreeCache(client,"/app2");

        //2. 注册监听
        treeCache.getListenable().addListener(new TreeCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
                System.out.println("节点变化了");
                System.out.println(event);
            }
        });

        //3. 开启
        treeCache.start();

        while (true){

        }
    }

}

 

标签:示例,Watch,new,public,client,org,apache,import,监听
From: https://www.cnblogs.com/weiduaini/p/17349907.html

相关文章

  • python三角网格划分示例
    python三角网格划分示例 importnumpyasnpimportturtle#输入三角形的边长length=float(input("Enterthelengthofthetriangle:"))#计算最短边、最长边和三角形个数short_side=lengthmax_side=length+lengthn=int(max_side/s......
  • 正的浮点数相加的示例程序 Verilog
    modulefloat_adder( input        clk, input       rst_n, input        en, input   [31:0]  aIn, input   [31:0]  bIn, outputreg     busy, outputreg   out......
  • 设计模式-原型模式-Java中使用示例-节日发送邮件活动
    场景设计模式-原型模式-浅克隆和深克隆在Java中的使用示例:https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/127576328上面初步记录了原型模式的使用示例,下面再记录一个银行节假日或者搞活动时发送邮件的例子。原型模式原型模式(PrototypePattern)的简单程度仅次......
  • golang中sync.Pool的使用示例
    先上代码:packagemainimport( "fmt" "sync")varpoolsync.Pooltypepersonstruct{ Namestring Ageint}funcinit(){ pool=sync.Pool{New:func()any{ returnnew(person) }}}funcmain(){ p:=pool.Get().(*person) p......
  • Google Guava常用的代码示例
    GoogleGuava谷歌出品的,非常实用。包含集合、并发、I/O、散列、缓存、字符串等。依赖:<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version></dependency>JoinerJoiner可以连接字符串。常用方法:Joine......
  • FileSystemWatcher 局域网中大文件的内部传输共享和处理方案
    在不使用其他软件的情况下共享,且自动清理。1、在服务器建了个临时文件夹共享,并且设置只可写入和读取,不可执行(删除)2、写服务源码附上usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Diagnostics;usingS......
  • MKL稀疏矩阵运算示例及函数封装
    IntelMKL库提供了大量优化程度高、效率快的稀疏矩阵算法,使用MKL库的将大型矩阵进行稀疏表示后,利用稀疏矩阵运算可大量节省计算时间和空间,但由于MKL中的原生API接口繁杂,因此将常用函数封装,便于后续使用,最后在实际例子中调用接口执行想要的矩阵运算。0稀疏矩阵稀疏矩阵是指矩阵......
  • thinkphp在模型中自动完成session赋值示例代码
    相信用过thinkphp的用户都知道thinkphp的模型可以完成很多辅助功能,比如自动验证、自动完成等,今天在开发中遇到自动完成中需要获取session值然后自动赋值的功能,具体看代码;classArticlelModelextendsModel{protected$_auto=array(array('addtime','time',1,'function'......
  • MKL普通矩阵运算示例及函数封装
    本示例将介绍MKL中的矩阵乘法和求逆,使用MKL进行此类大型矩阵运算可大量节省计算时间和空间,但由于MKL中的原生API接口繁杂,因此将常用函数封装,便于后续使用,最后在实际例子中调用接口执行想要的矩阵运算。1MKL矩阵乘法案例所用示例如下,矩阵A、B分别为\[A={\left[{\begin{array......
  • python matplotlib 散点图的拟合直线的简单示例
     #samplepointsX=[0,5,10,15,20]Y=[0,7,10,13,20]#solveforaandbdefbest_fit(X,Y):xbar=sum(X)/len(X)ybar=sum(Y)/len(Y)n=len(X)#orlen(Y)numer=sum([xi*yiforxi,yiinzip(X,Y)])-n*xbar*y......