82-java-zookeeper(2) -集群/curator/监控

一.zookeeper集群

1.集群搭建
1.创建一个文件夹,和复制配置zoo.cfg文件
2.修改cfg配置文件
3.在每一个文件夹中的dataDir下创建myid文件,并且根据配置文件中的信息,设置myid内容为服务器编号
4.参照1.2.3步骤,再配置一个服务器
5.启动三台服务器
	sh zkSevver.sh start xxx.cfg   #指定以哪个配置文件启动服务器
6.检查服务器状态
	sh zkServer.sh status xxx.cfg   #检查之地服务器的状态
2.zab协议

zookeeper automic Broadcast–zookeeper原子广播协议

参考文章:https://www.jianshu.com/p/2bceacd60b8a

3.zookeeper的leader选举
角色
	1.locking
	2.leader
	3.follower
	4.observer
服务器的启动时期的选举
	1.事务编号大的为leader
	2.事务编号相同,则myid号大的为leader
	3.如果两个台机器已经确地了leader,则第三台机器则自动为follower
服务器运行时期的选举
	如果运行时期leader宕机,则进行选举
	1.事务编号大的为leader
	2.事务编号相同,则myid号大的为leader
	3.如果两个台机器已经确地了leader,则第三台机器则自动为follower
4.observer的配置
1.在观察者服务的配置文件中配置:
	添加一行  peerType=observer
	集群中观察者的服务需要配置:  
	 server.4=127.0.0.1:2890:3890:observer   #server.4这是指的观察者的myid是4
2.在其他的服务配置文件中配置
	集群中观察者的服务需要配置: 
	 server.4=127.0.0.1:2890:3890:observer   #server.4这是指的观察者的myid是4
5.javaAPI连接集群

ZooKeeper zooKeeper = new ZooKeeper(),调用这个方法是,第一个参数中的值输入多个url,中间用逗号隔开即可:
ZooKeeper zooKeeper = new ZooKeeper(“118.190.58.27:2181,118.190.58.27:2182,118.190.58.27:2183”, 5000, null)

二.zookeeper的开源API—cerator

1.zookeeper原生api的缺点
  • 异步,编码不方便
  • watcher是一次性的
  • 不支持递归创建节点
  • 编码较难
2.curator连接对象的创建
  //创建连接对象
        CuratorFramework client = CuratorFrameworkFactory.builder()
                //指定连接的ip地址,这里连接的zookeeper集群
                .connectString("118.190.58.27:2181,118.190.58.27:2182,118.190.58.27:2183")
                //session超时时间
                .sessionTimeoutMs(5000)
                //超时重连策略,这里是超时重连异常,间隔3秒
                .retryPolicy(new RetryOneTime(3000))
                //命名空间,这个就是这个client对象的父节点.这个可以不指定
                .namespace("create")
                //构建连接对象
                .build();
        //打开连接
        client.start();

        System.out.println("连接已经创建");
        //关闭连接
        client.close();
3.RetryPolicy(重连策略)
  • RetryOneTIme
    #重连一次

  • RetryNTime
    #重连n次

  • RetryUntilElapsed
    #重连超时时间,超过多长时间没连上就不重连了

  • Exponent…
    #重连n次,每次时间间隔越来越常

4.增加/删除/修改/查询/查询子节点/判断是否存在
  • 创建节点
public class CuratorCreat {

    private CuratorFramework client;
    private static final String IP = "118.190.0.27:2181,118.190.0.27:2182,118.190.0.27:2183";

    @Before
    public void before(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        //创建连接对象
        client = CuratorFrameworkFactory.builder()
                //指定连接的ip地址,这里连接的zookeeper集群
                .connectString(IP)
                //session超时时间
                .sessionTimeoutMs(5000)
                //超时重连策略,这里是超时重连异常,间隔3秒
                .retryPolicy(retryPolicy)
                //命名空间,这个就是这个client对象的父节点.
                .namespace("create")
                //构建连接对象
                .build();
        //打开连接
        client.start();
    }

    @After
    public void after(){
        System.out.println("连接已关闭!!");
        client.close();
    }

    /**
     * 创建节点
     * @throws Exception
     */
    @Test
    public void create1() throws Exception{
        //创建节点
        client.create()
                //指定节点的类型为持久化节点
                .withMode(CreateMode.PERSISTENT)
                //指定节点的权限为  world:anyone
                .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                //参数一:节点路劲;当前节点路劲为:  /create/node1   #需要加上创建client指定的namespace
                //参数二:节点数据
                .forPath("/node1","gl".getBytes());

        System.out.println("结束");
    }

    /**
     * 递归创建节点
     * @throws Exception
     */
    @Test
    public void create2() throws Exception{
        client.create()
                .creatingParentsIfNeeded() // 如果父节点不存在,则创建父节点
                .withMode(CreateMode.PERSISTENT)
                .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                .forPath("/node2/node22","node22".getBytes());
        System.out.println("结束");
    }

    /**
     * 异步创建节点
     * @throws Exception
     */
    @Test
    public void create3() throws Exception{
        client.create()
                .creatingParentsIfNeeded() // 如果父节点不存在,则创建父节点
                .withMode(CreateMode.PERSISTENT)
                .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                .inBackground(new BackgroundCallback() { //异步执行
                    @Override
                    public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                        System.out.println(event.getPath());
                        System.out.println(event.getType());
                    }
                })
                .forPath("/node3/node31","node31".getBytes());
        //一定要线程睡眠,不然就直接关闭了连接了.创建节点则不成功.
        Thread.sleep(5000);
        System.out.println("结束");
    }


}

  • 删除节点
 /**
     * 删除节点
     */
    @Test
    public void delete() throws Exception{
        client.delete()
                .forPath("/node1"); //节点路劲

        System.out.println("结束");
    }

    /**
     * 指定版本号
     * 删除节点,
     */
    @Test
    public void delete2() throws Exception{
        client.delete()
                .withVersion(1) //指定版本号
                .forPath("/node1"); //节点路劲

        System.out.println("结束");
    }

    /**
     * 递归删除
     * 删除节点,指定版本号
     */
    @Test
    public void delete3() throws Exception{
        client.delete()
                .deletingChildrenIfNeeded() //递归删除
                .withVersion(-1) //指定版本号
                .forPath("/node1"); //节点路劲

        System.out.println("结束");
    }

    /**
     * 异步删除,递归删除
     * 删除节点,指定版本号
     */
    @Test
    public void delete4() throws Exception{
        client.delete()
                .deletingChildrenIfNeeded() //递归子节点删除
                .withVersion(-1) //指定版本号
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                        System.out.println(event.getPath());
                        System.out.println(event.getType());
                    }
                })
                .forPath("/node1"); //节点路劲

        Thread.sleep(3000);
        System.out.println("结束");
    }
  • 修改节点
 /**
     * 修改节点数据
     * @throws Exception
     */
    @Test
    public void set1() throws Exception{
        //修改节点数据
        client.setData()
                .forPath("/node1","111".getBytes());
        System.out.println("结束");
    }

    /**
     * 修改节点数据,增加版本号
     * @throws Exception
     */
    @Test
    public void set2() throws Exception{
        //修改节点数据
        client.setData()
                .withVersion(-1) //版本号,-1表示不指定版本号
                .forPath("/node1","222".getBytes());

        System.out.println("结束");
    }

    /**
     * 异步方式
     * 修改节点数据
     * @throws Exception
     */
    @Test
    public void set3() throws Exception{
        //修改节点数据
        client.setData()
                .withVersion(-1) //版本号,-1表示不指定版本号
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                        System.out.println(event.getPath());
                        System.out.println(event.getType());
                    }
                })
                .forPath("/node1","3333".getBytes());
        Thread.sleep(3000);
        System.out.println("结束");
    }
  • 获取节点
 /**
     * 读取数据
     * @throws Exception
     */
    @Test
    public void get() throws Exception{
        byte[] bytes = client.getData()
                .forPath("/node2");

        System.out.println(new String(bytes));
        System.out.println("结束");
    }

    /**
     * 读取数据,并将本节点的所有信息存放在stat中
     * @throws Exception
     */
    @Test
    public void get2() throws Exception{
        //状态值
        Stat stat = new Stat();
        byte[] bytes = client.getData()
                .storingStatIn(stat)  //将这个节点的状态值存放在stat对象中
                .forPath("/node2");

        System.out.println(new String(bytes));
        System.out.println("version: "+ stat.getVersion());
        System.out.println("结束");
    }

    /**
     * 异步读取
     * 读取数据,并将本节点的所有信息存放在stat中
     * @throws Exception
     */
    @Test
    public void get3() throws Exception{
         client.getData()
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                        System.out.println(event.getPath());
                        System.out.println(event.getType());
                    }
                })
                .forPath("/node2");

       Thread.sleep(3000);
        System.out.println("结束");
    }
  • 获取子节点
 /**
     * 读取子节点数据
     * @throws Exception
     */
    @Test
    public void getChildren() throws Exception{
        List<String> strings = client.getChildren()
                .forPath("/node2");
        for (String string : strings) {
            System.out.println(string);
        }
        System.out.println("结束");
    }

    /**
     * 异步方式
     * 读取子节点数据
     * @throws Exception
     */
    @Test
    public void getChildren2() throws Exception{
        client.getChildren()
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                        System.out.println(event.getPath());
                        System.out.println(event.getType());
                        List<String> children = event.getChildren();
                        for (String string : children) {
                            System.out.println(string);
                        }
                    }
                })
                .forPath("/node2");

        Thread.sleep(3000);
        System.out.println("结束");
    }

  • 判断节点是否存在
 /**
     * 判断节点是否存在
     * @throws Exception
     */
    @Test
    public void exist1() throws Exception{
        Stat stat = client.checkExists()
                .forPath("/node2");

        System.out.println(stat);
        System.out.println("结束");
    }


    /**
     * 异步方式
     * 判断节点是否存在
     * @throws Exception
     */
    @Test
    public void exist2() throws Exception{
        client.checkExists()
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                        System.out.println(event.getPath());
                        System.out.println(event.getType());
                        System.out.println(event.getStat().getVersion());
                    }
                })
                .forPath("/node2");

        Thread.sleep(3000);
        System.out.println("结束");
    }

5.watcherAPI

    /**
     *监听该节点
     */
    @Test
    public void watcher1() throws Exception{
        //监视某个节点数据的变化
        //参数一:连接对象
        //参数二:监视的节点路劲
        NodeCache nodeCache = new NodeCache(client,"/watcher1");

        //启动监视器对象
        nodeCache.start();

        nodeCache.getListenable().addListener(new NodeCacheListener() {
            //节点变化时回调的方法
            @Override
            public void nodeChanged() throws Exception {
                System.out.println(nodeCache.getCurrentData().getPath());
                System.out.println(new String(nodeCache.getCurrentData().getData()));
            }
        });
        Thread.sleep(50000);
        System.out.println("结束");
        //关闭监听器对象
        nodeCache.close();
    }

    /**
     * 监听子节点变化情况
     */
    @Test
    public void watcher2() throws Exception{
        //监视子节点的变化
        //参数一:连接对象
        //参数二:监视的节点路劲
        //参数三:事件中是否可以获取节点的数据
        PathChildrenCache pathChildrenCache = new PathChildrenCache(client,"/watcher1",true);
        //开启监听对象
        pathChildrenCache.start();

        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                System.out.println(event.getType());
                System.out.println(event.getData().getPath());
                System.out.println(event.getData().getData());
            }
        });
        Thread.sleep(100000);
        System.out.println("结束");
        //关闭监听器对象
        pathChildrenCache.close();

    }
6.事务
/**
     * 测试开启事务,要么全部成功,要么全部是失败
     */
    @Test
    public void transaction() throws Exception{
        //开启事务
        client.inTransaction()
                //创建一个Tnode1节点
                .create().forPath("/tNode1","tnode1".getBytes())
                .and()
                //创建一个tNode2节点
                .setData().forPath("/tNode2","tNode2".getBytes())
                .and()
                //事务提交
                .commit();
    }
7.分布式锁
  /**
     * 排他锁
     */
    @Test
    public void Lock1() throws Exception{
        //排他锁
        InterProcessMutex mutex = new InterProcessMutex(client,"/lock1");
        System.out.println("等待获取锁对象");
        //获取锁
        mutex.acquire();

        //让获取到锁的对象慢慢输出10个数
        for (int i = 0; i < 10; i ++){
            Thread.sleep(1000);
            System.out.println(i);
        }
        //释放锁
        mutex.release();
        System.out.println("等待释放锁");
    }

    /**
     * 读写锁
     * 加读锁
     */
    @Test
    public void Lock2() throws Exception{
        //读写锁对象
        InterProcessReadWriteLock readWriteLock = new InterProcessReadWriteLock(client, "/lock2");
        //获取读锁
        InterProcessMutex readLock = readWriteLock.readLock();
        System.out.println("等待获取锁对象");

        //添加读锁
        readLock.acquire();
        //让获取到锁的对象慢慢输出10个数
        for (int i = 0; i < 10; i ++){
            Thread.sleep(2000);
            System.out.println(i);
        }

        //释放锁
        readLock.release();
        System.out.println("等待释放锁");

    }

    /**
     * 读写锁
     * 加写锁
     */
    @Test
    public void Lock3() throws Exception{
        //读写锁对象
        InterProcessReadWriteLock readWriteLock = new InterProcessReadWriteLock(client, "/lock2");
        //获取写锁
        InterProcessMutex writeLock = readWriteLock.writeLock();
        System.out.println("等待获取锁对象");
        //添加锁
        writeLock.acquire();
        //让获取到锁的对象慢慢输出10个数
        for (int i = 0; i < 10; i ++){
            Thread.sleep(2000);
            System.out.println(i);
        }

        //释放锁
        writeLock.release();
        System.out.println("等待释放锁");
    }

监控

监控命令

  • conf
  • cons
  • crst
  • dump
  • envi
  • ruok
  • 图形化页面工具
  • 图形化监控工具(taokeepeer)
    #淘宝开发的zookeeper监控工具
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值