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 需要重复注册
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.4.6</version>
</dependency>
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

<dependency>
    <groupId>com.101tec</groupId>
    <artifactId>zkclient</artifactId>
    <version>0.2</version>
</dependency>
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

<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>2.11.0</version>
</dependency>
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<CuratorTransactionResult> 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();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值