Zookeeper:Zookeeper JavaAPI操作与分布式锁

文章目录

一、Zookeeper JavaAPI操作

1、Curator介绍

  • Curator是Apache Zookeeper的Java客户端。
  • 常见的Zookeeper Java API:
    • 原生Java API。
    • ZkClient。
    • Curator。
  • Curator项目目标是简化Zookeeper客户端的使用。
  • Curator最初是Netfix研发的,后来捐献了Apache基金会,目前是Apache的顶级项目。
  • 官网:https://curator.apache.org/docs/about

2、创建、查询、修改、删除节点

bash 复制代码
public class CuratorTest {
    private CuratorFramework client;

    @Before
    public void init() {
        // 1、方式一
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 10);
        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient("localhost:2181", 60 * 1000, 15 * 1000, retryPolicy);

        // 2、方式二
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("localhost:2181")
                .sessionTimeoutMs(60 * 1000)
                .connectionTimeoutMs(15 * 1000)
                .retryPolicy(retryPolicy)
                .namespace("test")
                .build();
        // 开启连接
        client.start();
        this.client = client;
    }

    /**
     * 1、基本创建:client.create().forPath("/app1")
     * 2、创建节点,带有数据:client.create().forPath("/app1", data)
     * 3、设置节点的类型: client.create().withMode(CreateMode.EPHEMERAL).forPath("/app1")
     * 4、创建多级节点: client.create().creatingParentsIfNeeded().forPath("/app1/app2")
     */
    @Test
    public void testCreate() {
        // 1、基本创建
        // 如果创建节点,没有指定数据,则默认将当前客户端的ip作为数据存储
        try {
            String path = client.create().forPath("/app1");
            System.out.println(path);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

 /**
     * 查询节点:
     * 1、查询数据:get
     * 2、查询子节点: ls
     * 3、查询节点状态信息: ls -s
     */
    @Test
    public void testQueryData() {
        // 1、查询数据: get
        try {
            byte[] data = client.getData().forPath("/app1");
            System.out.println(new String(data));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void testQueryChildren() {
        // 查询子节点: ls
        try {
            List<String> stringList = client.getChildren().forPath("/");
            System.out.println(stringList);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void testQueryState() {
        // 查询节点状态信息: ls -s
        Stat status = new Stat();
        try {
            client.getData().storingStatIn(status).forPath("/app1");
            System.out.println(status);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

  /**
     * 修改数据:
     * 1、修改数据。
     * 2、根据版本修改
     */
    @Test
    public void testSet() {
        // 修改数据
        try {
            client.setData().forPath("/app1", "haha".getBytes());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void testSetForVersion() throws Exception {
        // 根据版本修改
        Stat stat = new Stat();
        // 查询节点状态信息: ls -s
        client.getData().storingStatIn(stat).forPath("/app1");

        int version = stat.getVersion();
        client.setData().withVersion(version).forPath("/app1", "hehe".getBytes());
    }
 /**
     * 删除节点:delete、deleteall
     * 1、删除单个节点
     * 2、删除带有子节点的节点
     * 3、必须成功的删除: 为了防止网络抖动。本质就是重试。
     * 4、回调
     */
    @Test
    public void testSingleDelete() throws Exception {
        // 1、删除单个节点
        client.delete().forPath("/app1");

        // 2、删除带有子节点的节点
        client.delete().deletingChildrenIfNeeded().forPath("/app1");

        // 3、必须成功删除
        client.delete().guaranteed().forPath("/app1");

        //4、回调
        client.delete().guaranteed().inBackground((client, event) -> {
            System.out.println("我被删除了");
            System.out.println(event);
        }).forPath("/app1");
    }

    @After
    public void close() {
        if (client != null) {
            client.close();
        }
    }
}

3、Watch事件监听

  • Zookeeper允许用户在指定节点上注册一些Watcher,并且在一些特定事件触发的时候,Zookeeper服务端会将事件通知到感兴趣的客户端上去,该机制是Zookeeper实现分布式协调服务的重要性。
  • Zookeeper中引入了Watcher机制来实现了发布/订阅功能,能够让多个订阅者同时监听某一个对象,当一个对象自身状态变化时,会通知所有订阅者。
  • Zookeeper原生支持通过注册Watcher来进行事件监听,但是其使用并不是特别方便需要开发人员自己反复注册Watcher,比较繁琐。
  • Curator引入了Cache来实现对Zookeeper服务端事件的监听。
  • Zookeeper提供了三种Watcher:
    • NodeCache:只是监听某一个特定的节点。
    • PathChildrenCache:监控一个ZNode的子节点。
    • TreeCache:可以监控整个树上所有节点,类似于PathChildrenCache和NodeCache的组合。

二、Zookeeper分布式锁原理

相关推荐
jessecyj2 小时前
【RabbitMQ】超详细Windows系统下RabbitMQ的安装配置
windows·分布式·rabbitmq
行者-全栈开发5 小时前
拆解高可用CRM网站的容灾设计与云原生实践
微服务·云原生·异地多活·监控告警·高可用设计·crm架构·容灾演练
阿维的博客日记6 小时前
分布式事务代码
分布式
Crazy________6 小时前
4.13docker仓库registry
mysql·算法·云原生·eureka
小义_1 天前
【Kubernetes】(五) pod2
linux·云原生·容器·kubernetes
_waylau1 天前
鸿蒙架构师修炼之道-面向对象的分布式架构
分布式·华为·架构·架构师·harmonyos·鸿蒙
雨奔1 天前
Kubernetes 对象标识详解:Name、UID、Label
云原生·容器·kubernetes
Francek Chen1 天前
【大数据存储与管理】NoSQL数据库:03 NoSQL与关系数据库的比较
大数据·数据库·分布式·nosql
老实巴交的麻匪1 天前
Exception异常架构设计:系统性异常处理的思维革命(05)
运维·云原生·架构
FeBaby1 天前
Java 高并发场景下 Redis 分布式锁(UUID+Lua)最佳实践
java·redis·分布式