栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

2. Zookeeper 客户端

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2. Zookeeper 客户端

1. 客户端指令

create [-e][-s] path data [acl]:-e:临时节点;-s:顺序节点
set [-s][-v version] path data:-v:指定版本号更新
get [-s][-w] path:-s:列出节点详情;-w:添加 watcher
ls [-s][-w][-R] path:-s:列出节点详情;-w:添加 watcher;-R:列出节点的级联节点
stat [-w] path:-w:添加 watcher
delete path:删除节点
deleteall path:删除级联节点

quit:退出客户端

ACL:
5 种权限:create,read,write,delete,admin
addauth digest mustang:123:新增用户认证
setAcl path auth:mustang:123:r:对用户节点设置权限
getAcl path:查看用户节点权限

2. 客户端 API 1. 原生客户端

原生客户端缺点:

  1. 会话连接是异步的
  2. Watcher 需要重复注册

    org.apache.zookeeper
    zookeeper
    3.4.6

public class MyWatcher implements Watcher {

    private CountDownLatch cdl;

    public MyWatcher(CountDownLatch cdl) {
        this.cdl = cdl;
    }

    @Override
    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            if (Event.EventType.None == event.getType() && null == event.getPath()) {
                cdl.countDown();
                System.out.println(event.getState());
                System.out.println("Zookeeper session established");
            } else if (Event.EventType.NodeCreated == event.getType()) {
                System.out.println("success create znode");
            } else if (Event.EventType.NodeDataChanged == event.getType()) {
                System.out.println("success change znode: " + event.getPath());
            } else if (Event.EventType.NodeDeleted == event.getType()) {
                System.out.println("success delete znode");
            } else if (Event.EventType.NodeChildrenChanged == event.getType()) {
                System.out.println("NodeChildrenChanged");
            }
        }
    }
}

public class ZookeeperDemo {

    private static String connectStr = "192.168.67.139:2184";
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) throws IOException, InterruptedException {
        // 建立连接是一个异步过程
        ZooKeeper zooKeeper = new ZooKeeper(connectStr, 5000, new MyWatcher(countDownLatch));
        countDownLatch.await();

        nodeCreate(zooKeeper, "/demo1");
        nodeChange(zooKeeper, "/demo1", "Jack2");
        nodeDelete(zooKeeper, "/demo1");
    }

    private static void nodeDelete(ZooKeeper client, String path) {
        try {
            client.exists(path, true);
            client.delete(path, -1);
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void nodeChange(ZooKeeper client, String path, String value) {
        try {
            client.exists(path, true);
            client.setData(path, value.getBytes(), -1);

            client.getData(path, true, new Stat());
            client.setData(path, value.getBytes(), -1);
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void nodeCreate(ZooKeeper client, String path) {
        try {
            client.create(path, "mustang".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
2. zkclient

    com.101tec
    zkclient
    0.2

public class ZkClientDemo {
    private static String connectStr = "192.168.67.139:2184";

    public static void main(String[] args) throws InterruptedException {
        ZkClient zkClient = new ZkClient(connectStr, 5000);

        String path = "/demo2";
        if (!zkClient.exists(path)) {
            zkClient.createPersistent(path, "mustang");
        }

        System.out.println(zkClient.readData(path).toString());

        //事件监听
        zkClient.subscribeDataChanges(path, new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {
                System.out.println(dataPath + "数据变更" + data);
            }

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {

            }
        });

        zkClient.writeData(path, "Jack1");

        TimeUnit.SECONDS.sleep(1);
        zkClient.writeData(path, "Jack2");

        TimeUnit.SECONDS.sleep(1);
        System.out.println(zkClient.readData(path).toString());
    }
}
3. curator

    org.apache.curator
    curator-recipes
    2.11.0

public class CuratorDemo {

    public static String node = "/curator/mustang";

    public static void main(String[] args) {
        CuratorFramework client = CuratorUtil.getInstance();
        //启动连接
        client.start();
        create(client);
        query(client);
        update(client);
        createSync(client);
        transation(client);
    }

    private static void transation(CuratorFramework client) {
        try {
            Collection results = client.inTransaction()
                    .create()
                    .withMode(CreateMode.EPHEMERAL)
                    .forPath("/transaction", "ww".getBytes())
                    .and()
                    .setData()
                    .forPath("/transaction", "ww-modify".getBytes())
                    .and()
                    .commit();

            for (CuratorTransactionResult result : results) {
                OperationType type = result.getType();
                System.out.println(type.name());
                System.out.println(result.getForPath() + "==" + result.getResultPath() + "==" + result.getResultStat());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void createSync(CuratorFramework client) {
        try {
            client.create().creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL)
                    .inBackground(new BackgroundCallback() {
                        @Override
                        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                            System.out.println(event.getName() + ":" + event.getPath());
                        }
                    }).forPath("/createsync", "sync".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (client != null) {
                client.close();
            }
        }
    }

    private static void delete(CuratorFramework client) {
        try {
            Void aVoid = client.delete().deletingChildrenIfNeeded().withVersion(-1).forPath(node);
            System.out.println("delete-->");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (client != null) {
                client.close();
            }
        }
    }


    private static void update(CuratorFramework client) {
        try {
            Stat stat = client.setData().withVersion(-1).forPath(node, "rr".getBytes());
            System.out.println("update-->" + stat);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (client != null) {
                client.close();
            }
        }
    }

    private static void query(CuratorFramework client) {
        try {
            byte[] bytes = client.getData().storingStatIn(new Stat()).forPath(node);
            System.out.println("query-->" + new String(bytes));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (client != null) {
                client.close();
            }
        }
    }

    private static void create(CuratorFramework client) {
        try {
            String path = client.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT)
                    .forPath(node, "123".getBytes());
            System.out.println(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/822008.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号