zk节点创建及Treecache监听

1.引入jar包


	org.apache.curator
	curator-framework
	2.11.1


	org.apache.curator
	curator-recipes
	2.10.0

2.创建ClientUtil类

package com.example.demo2;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.KeeperException;
import java.util.concurrent.TimeUnit;

public class ClientUtil {

    public static CuratorFramework getInstance() {
        CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
                .connectString("192.168.232.5:2181")
                .retryPolicy(new ExponentialBackoffRetry(1000, 2, 10));

        builder.sessionTimeoutMs(60000);
        builder.connectionTimeoutMs(15000);
        CuratorFramework client = builder.build();

        client.start();
        try {
            if (!client.blockUntilConnected(1000, TimeUnit.MILLISECONDS)) {
                client.close();
                throw new KeeperException.OperationTimeoutException();
            }
            //CHECKSTYLE:OFF
        } catch (final Exception ex) {
            //CHECKSTYLE:ON
        }
        return client;
    }
}

3.监听

package com.example.demo2;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 监听运行
 */
@Component
public class BeanInitRunner implements CommandLineRunner {
    @Autowired
    BeanTreeCacheListener beanTreeCacheListener;
    @Override
    public void run(String... args) throws Exception {
        TreeCache treeCache = new TreeCache(ClientUtil.getInstance(), "/mm");
        treeCache.getListenable().addListener(beanTreeCacheListener);
        treeCache.start();
    }

}
package com.example.demo2;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.springframework.stereotype.Component;

@Component
public class BeanTreeCacheListener implements TreeCacheListener {
    @Override
    public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent treeCacheEvent) throws Exception {
        ChildData data = treeCacheEvent.getData();
        if (data == null)
            return;
        String path = data.getPath();
        switch (treeCacheEvent.getType()) {
            case NODE_ADDED:
                if (path.split("/").length == 3) {
                    String val = new String(curatorFramework.getData().forPath(path), "UTF-8");
                    System.out.println("NODE_ADDED " + val);
                }
                break;
            case NODE_UPDATED:
                if (path.split("/").length == 3) {
                    String val = new String(curatorFramework.getData().forPath(path), "UTF-8");
                    System.out.println("NODE_UPDATED " + val);
                }
                break;
            case NODE_REMOVED:
                if (path.split("/").length == 3) {
                    System.out.println("NODE_REMOVED " + path);
                }
                break;

            default:
                break;
        }
    }
}

4.创建节点

package com.example.demo2;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class BeanCRUD implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        try {
            String path = "/mm/test";
            CuratorFramework client = ClientUtil.getInstance();
            client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, "hello zk".getBytes());
//            client.inTransaction().check().forPath(path).and().setData().forPath(path, "hello zk too".getBytes());
//            client.delete().deletingChildrenIfNeeded().forPath(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}




你可能感兴趣的:(zk节点创建及Treecache监听)