对Apache Curator的简单封装

操作封装类

package com.flynn.curator;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

/**
 * Zookeeper客户端封装
 */
public class ZookeeperClient {
    //创建连接实例
    private CuratorFramework client = null;
    //节点事件监听
    private Map<String, TreeCache> nodeListeners = new ConcurrentHashMap<String, TreeCache>();

    public ZookeeperClient(String connectString,int sessionTimeoutMs, int connectionTimeoutMs, RetryPolicy retryPolicy) throws Exception {
        //创建 CuratorFrameworkImpl实例
        client = CuratorFrameworkFactory.newClient(connectString, sessionTimeoutMs, connectionTimeoutMs, retryPolicy);
        //启动
        client.start();
    }
    
    /**
     * 增加某个节点的监听
     * @param path
     * @param callback
     * @throws Exception 
     */
    public void addListener(String path ,Consumer<TreeCacheEvent> callback) throws Exception {
        TreeCache treeCache = new TreeCache(client, path);
        nodeListeners.put(path,treeCache);
        //启动监听
        treeCache.start();
        // 没有开启模式作为入参的方法
        treeCache.getListenable().addListener(new TreeCacheListener(){
            @Override
            public void childEvent(CuratorFramework client, TreeCacheEvent event)
                    throws Exception {
                try {
                    callback.accept(event);
                } finally {
                    if(event.getType() == Type.NODE_REMOVED) {
                        String path = event.getData().getPath();
                        if(path!=null) {
                            removeLisner(path);
                            System.err.println("Delete Listener: "+path);
                        }
                    }
                }
//                switch(event.getType()) {
//                case NODE_ADDED: 
//                    System.out.println("tree:发生节点添加" + event.getData().toString() ); break;
//                case NODE_UPDATED:
//                    System.out.println("tree:发生节点更新"); 
//                    break;
//                case NODE_REMOVED:
//                    System.out.println("tree:发生节点删除"); 
//                   
//                    break;
//                case CONNECTION_SUSPENDED: 
//                    break;
//                case CONNECTION_RECONNECTED:
//                    break;
//                case CONNECTION_LOST:
//                    break;
//                case INITIALIZED:
//                    System.out.println("初始化的操作"); break;
//                default:
//                    break;
//                }
            }
        });
    }
    /**
     * 删除此节点上的监听
     * @param path
     */
    private void removeLisner(String path) {
        TreeCache treeCache = nodeListeners.remove(path);
        if(treeCache!=null) {
            treeCache.close();
        }
    }
    /**
     * 创建指定节点,若父节点不存在则自动创建父节点
     * @param path
     * @param data
     * @param mode
     * @throws Exception
     */
    public String createNode(String path,String data,CreateMode mode) throws Exception {
//      client.create().creatingParentContainersIfNeeded().withMode(mode).forPath(path, data.getBytes(Charset.forName("UTF-8")));
        return createNode(path, data.getBytes(Charset.forName("UTF-8")), mode);
    }
    public String createNode(String path,byte[] data,CreateMode mode) throws Exception {
        return client.create().creatingParentContainersIfNeeded().withMode(mode).forPath(path, data);
    }
    /**
     * 设置一个节点,当节点不存在时,会创建一个永久节点
     * @param path
     * @param data
     * @throws Exception
     */
    public String setNode(String path,String data) throws Exception {
        return setNode(path, data, CreateMode.PERSISTENT);
    }
    /**
     * 设置节点的内容,若节点不存在,则创建此节点
     * @param path
     * @param data
     * @param mode
     * @throws Exception
     */
    public String setNode(String path,String data,CreateMode mode) throws Exception {
        return setNode(path, data.getBytes(Charset.forName("UTF-8")), mode);
    }
    public String setNode(String path,byte[] data,CreateMode mode) throws Exception {
        if(checkExists(path)) {
            client.setData().forPath(path, data);
            return path;
        }else {
            return createNode(path,data,mode);
        }
    }
    /**
     * 检测节点是否存在
     * @param path
     * @return
     * @throws Exception
     */
    public boolean checkExists(String path) throws Exception {
        Stat stat = client.checkExists().forPath(path);
        if(stat!=null) {
            return true;
        }
        return false;
    }
    /**
     * 获取节点内容
     * @param path
     * @return
     * @throws Exception
     */
    public Optional<String> getNode(String path) throws Exception {
        byte[] bytes = client.getData().forPath(path);
        return Optional.ofNullable(bytes != null ? new String(bytes,Charset.forName("UTF-8")) : null);
    }
    /**
     * 
     * @param path
     * @return
     * @throws Exception
     */
    public List<String> getChildren(String path) throws Exception {
        return client.getChildren().forPath(path);
    }
    /**
     * 获取子节点数据
     * @param path
     * @return
     * @throws Exception
     */
    public Map<String, String> getChildrenData(String path) throws Exception{
        List<String> children = getChildren(path);
        return children.stream().collect(Collectors.toMap(key->key, childName->{
            try {
                return getNode(path+"/"+childName).get();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }));
    }
    /**
     * 删除节点
     * @param path
     * @throws Exception
     */
    public void deleteNode(String path) throws Exception {
        //删除该节点
        client.delete().forPath(path);
    }
    /**
     * 删除节点自身及子节点
     * @param path
     * @throws Exception
     */
    public void deleteNodeChildren(String path) throws Exception {
        //级联删除子节点
        client.delete().guaranteed().deletingChildrenIfNeeded().forPath(path);
    }
    /**
     * 事务处理
     * @param processeres
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public List<CuratorTransactionResult> transaction(Function<TransactionOp , CuratorOp> ... processeres) throws Exception {
        TransactionOp transactionOp = client.transactionOp();
        List<CuratorOp> curatorOps = new ArrayList<CuratorOp>();
        Arrays.stream(processeres).forEach(func->{
            CuratorOp curatorOp = func.apply(transactionOp);
            if(curatorOp != null) {
                curatorOps.add(curatorOp);
            }
        });
        CuratorOp[] ops = new CuratorOp[curatorOps.size()];
        curatorOps.toArray(ops);
        List<CuratorTransactionResult> results = client.transaction()
                .forOperations(ops);
        return results;
//      //遍历输出结果
//      for(CuratorTransactionResult result : results){
//          System.out.println("执行结果是: " + result.getForPath() + "--" + result.getType());
//      }
    }
    public static CuratorOp curatorOpForCreate(TransactionOp transactionOp,String path,String data,CreateMode mode) {
        try {
            return transactionOp.create().withMode(mode).forPath(path, data.getBytes(Charset.forName("UTF-8")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static CuratorOp curatorOpForSet(TransactionOp transactionOp,String path,String data) {
        try {
            return transactionOp.setData().forPath(path, data.getBytes(Charset.forName("UTF-8")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static CuratorOp curatorOpForDelete(TransactionOp transactionOp,String path) {
        try {
            return transactionOp.delete().forPath(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static CuratorOp curatorOpForCheck(TransactionOp transactionOp,String path) {
        try {
            return transactionOp.check().forPath(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

测试用例

package com.flynn.curator;

import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class ZookeeperClientUseCase {   

    private ZookeeperClient zookeeperClient = null;
    @Before
    public void before() throws Exception {
        
        zookeeperClient = new ZookeeperClient("127.0.0.1:2181", 30*1000, 3*1000, new ExponentialBackoffRetry(1000, 3));
    }
    
    @Test
    public void testCreate() throws Exception {
        zookeeperClient.createNode("/testzookeeper/names", "flynn1,flynn2,flynn3", CreateMode.PERSISTENT);
    }
    @Test
    public void testGet() throws Exception {
        
        //路径存在时
        String data = zookeeperClient.getNode("/testzookeeper/names").orElseGet(null);
        System.out.println(data);
        System.out.println("------------");
        
        //当节点不存在时抛出异常
        //KeeperException.NoNodeException
        System.out.println(zookeeperClient.getNode("/testzookeeper/ages").orElse(null));
    }
    @Test
    public void testCheckExists() throws Exception {
        Assert.assertEquals(zookeeperClient.checkExists("/testzookeeper/ages"), false);
        Assert.assertEquals(zookeeperClient.checkExists("/testzookeeper/names"), true);
    }
    @Test
    public void testDelete() throws Exception {
        zookeeperClient.deleteNode("/testzookeeper/names");
    }
    @Test
    public void testChildren() throws Exception {
        System.out.println(zookeeperClient.getChildren("/testzookeeper"));
    }
    @Test
    public void testChilrenData() throws Exception {
        System.out.println(zookeeperClient.getChildrenData("/testzookeeper"));
    }
    @Test
    public void testListener() throws Exception {
        zookeeperClient.addListener("/testzookeeper/names", (TreeCacheEvent event)->{
            
            System.out.println("--------------");
            System.out.println(event.getType());
            System.out.println(event.getData().getPath());
            System.out.println("^^^^^^^^^^^^^^^");
        });
        
//      zookeeperClient.setNode("/testzookeeper/names", "chester1,chester2,chester3,cheste");
        zookeeperClient.setNode("/testzookeeper/names","xxx,ewewe,cerewr");
        zookeeperClient.setNode("/testzookeeper/names/subnames","dhtia,ehwei,thhe");
        zookeeperClient.setNode("/testzookeeper/names/subnames/xx","meitian,teiyw");
//      zookeeperClient.deleteNode("/testzookeeper/names/subnames");
        zookeeperClient.deleteNodeChildren("/testzookeeper/names");
        Thread.currentThread().join();
    }
    @Test
    public void testCreateSequNode() throws Exception {
        zookeeperClient.createNode("/testzookeeper/names", "xxx,ewewe,cerewr1", CreateMode.PERSISTENT_SEQUENTIAL);
        zookeeperClient.createNode("/testzookeeper/names", "xxx,ewewe,cerewr2", CreateMode.PERSISTENT_SEQUENTIAL);
        zookeeperClient.createNode("/testzookeeper/names", "xxx,ewewe,cerewr3", CreateMode.PERSISTENT_SEQUENTIAL);
        zookeeperClient.createNode("/testzookeeper/names", "xxx,ewewe,cerewr4", CreateMode.PERSISTENT_SEQUENTIAL);
    }
    @Test
    public void testChildrenData() throws Exception {
        System.out.println(zookeeperClient.getChildrenData("/testzookeeper"));
    }
    
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,186评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,858评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,620评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,888评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,009评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,149评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,204评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,956评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,385评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,698评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,863评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,544评论 4 335
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,185评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,899评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,141评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,684评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,750评论 2 351

推荐阅读更多精彩内容

  • 【文章摘要】 面向对象的软件测试摘 要: 如今,面向对象开发技术正大力地的推动着软件产业的快速发展。在保证软件产品...
    西边人阅读 3,108评论 0 2
  • 相关文章: 《再说说APP测试设计-1》《再说APP测试设计-2》《关于ad hoc test》《干了这碗蛋炒饭 ...
    慧众rodman阅读 3,204评论 1 34
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,094评论 1 32
  • 运营笔记侠 本文笔记来源于插座学院:何川老师演讲 第四讲:企业新媒体典型文案 最后给大家讲一点企业新媒体的文案的案...
    Jack遇见冰山阅读 595评论 0 1
  • 六边形架构是一种设计风格,通过分层实现核心逻辑与外部对象隔离。其核心逻辑是业务模块,外部元素是整合点,比如数据库、...
    java菜阅读 454评论 0 1