【SpringBoot】整合Zookeeper

这篇具有很好参考价值的文章主要介绍了【SpringBoot】整合Zookeeper。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、引言

使用原生的zookeeper时候会遇到watcher一次注册生效一次等情况,因此使用curator

curator是Netflix公司开源的一个 zookeeper客户端原生API接口上进行了包装,解决了很多问题并提供Zookeeper分布式锁服务、集群领导选举、共享计数器、缓存机制、分布式队列等的应用的抽象封装

一、引入依赖

<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.6.2</version>
</dependency>
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-framework</artifactId>
    <version>5.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>5.2.0</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>2.0.10</version>
</dependency>

二、编写客户端

要改Windows的host文件。host文件位置是C:\Windows\System32\drivers\etc
springboot集成zookeeper,SpringBoot,java-zookeeper,zookeeper,spring boot文章来源地址https://www.toymoban.com/news/detail-608487.html

2.1、ZookeeperConfig

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ZookeeperConfig {

    //集群地址,分割不能有空格 在程序里写connectString不可使用ip,必须使用主机名
    private String connectString = "master:2181,slave1:2181,slave2:2181";
    //连接超时时间
    private int sessionTimeout = 5000;
    //会话存活时间,根据业务灵活指定
    private Integer sessionTimeOut=5000;
    //重试机制时间参数
    private Integer sleepMsBetweenRetry=1000;
    //重试机制重试次数
    private Integer maxRetries=3;
    //命名空间(父节点名称)
    private String namespace="";

    /**
     - `session`重连策略
     - `RetryPolicy retry Policy = new RetryOneTime(3000);`
     - 说明:三秒后重连一次,只重连一次
     - `RetryPolicy retryPolicy = new RetryNTimes(3,3000);`
     - 说明:每三秒重连一次,重连三次
     - `RetryPolicy retryPolicy = new RetryUntilElapsed(1000,3000);`
     - 说明:每三秒重连一次,总等待时间超过个`10`秒后停止重连
     - `RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3)`
     - 说明:这个策略的重试间隔会越来越长
     - 公式:`baseSleepTImeMs * Math.max(1,random.nextInt(1 << (retryCount + 1)))`
     - `baseSleepTimeMs` = `1000` 例子中的值
     - `maxRetries` = `3` 例子中的值
     */
    @Bean("curatorClient")
    public CuratorFramework curatorClient() throws Exception {
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(connectString)
                .connectionTimeoutMs(sessionTimeout)
                .sessionTimeoutMs(sessionTimeOut)
                //session重连策略
                .retryPolicy(new ExponentialBackoffRetry(sleepMsBetweenRetry,maxRetries))
                //设置命名空间 在操作节点的时候,会以这个为父节点
                .namespace(namespace)
                .build();
        client.start();

        //注册监听器
        ZookeeperWatches watches = new ZookeeperWatches(client);
        watches.znodeWatcher();
        watches.znodeChildrenWatcher();
        return client;
    }
}

2.2、ZookeeperWatches

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.zookeeper.data.Stat;

public class ZookeeperWatches {

    private CuratorFramework client;

    public ZookeeperWatches(CuratorFramework client) {
        this.client = client;
    }

    public void znodeWatcher() throws Exception {
        NodeCache nodeCache = new NodeCache(client, "/");
        nodeCache.start();
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                System.out.println("=======节点改变===========");
                String path = nodeCache.getPath();
                String currentDataPath = nodeCache.getCurrentData().getPath();
                String currentData = new String(nodeCache.getCurrentData().getData());
                Stat stat = nodeCache.getCurrentData().getStat();
                System.out.println("path:"+path);
                System.out.println("currentDataPath:"+currentDataPath);
                System.out.println("currentData:"+currentData);
            }
        });
        System.out.println("节点监听注册完成");
    }

    public void znodeChildrenWatcher() throws Exception {
        PathChildrenCache pathChildrenCache = new PathChildrenCache(client, "/",true);
        pathChildrenCache.start();
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                System.out.println("=======节点子节点改变===========");
                PathChildrenCacheEvent.Type type = event.getType();
                String childrenData = new String(event.getData().getData());
                String childrenPath = event.getData().getPath();
                Stat childrenStat = event.getData().getStat();

                System.out.println("子节点监听类型:"+type);
                System.out.println("子节点路径:"+childrenPath);
                System.out.println("子节点数据:"+childrenData);
                System.out.println("子节点元数据:"+childrenStat);

            }
        });
        System.out.println("子节点监听注册完成");
    }
}

2.3、ZookeeperController

@RestController
@RequestMapping(value = "/zookeeper")
public class ZookeeperController {

    @Resource(name = "curatorClient")
    private CuratorFramework client;

    @RequestMapping("/createZnode")
    public String createZnode(){
        String path = "/nacl";
        String data = "shuaige";
        List<ACL> aclList = new ArrayList<>();
        Id id = new Id("world", "anyone");
        aclList.add(new ACL(ZooDefs.Perms.ALL, id));
        try {
            client.create()
                    .creatingParentsIfNeeded()  //没有父节点时 创建父节点
                    .withMode(CreateMode.PERSISTENT)  //节点类型
                    .withACL(aclList)   //配置权限
                    .forPath(path, data.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            return "节点创建失败"+e.getMessage();
        }
        return "节点创建成功";
    }

    @RequestMapping("/selectZnode")
    public String  selectZnode(){
        HashMap<String,String> hashMap=new HashMap();
        String path="/nacl";
        Stat stat;
        try {
            stat = client.checkExists().forPath(path);
            if (stat == null) {
                hashMap.put("Error","不存在该节点");
            }
            String dataString = new String(client.getData().forPath(path));
            hashMap.put(path, dataString);
            hashMap.put("stat", stat.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(hashMap);
    }
    
    @RequestMapping("/selectChildrenZnode")
    public String selectChildrenZnode(){
        Map<String, String> hashMap = new HashMap<>();
        String path="/";
        try {
            List<String> list = client.getChildren().forPath(path);
            for (String s : list) {
                String dataString = new String(client.getData().forPath(path+s));
                hashMap.put(path+s, dataString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(hashMap);
    }
    
    @RequestMapping("/setData")
    public String setData() {
        String path="/nacl";
        String data="big";
        Integer version=0;
        HashMap<String,String> hashMap=new HashMap<>();
        try {
            Stat stat = client.setData().withVersion(version).forPath(path, data.getBytes());
            hashMap.put("success", "修改成功");
            hashMap.put("version", String.valueOf(stat.getVersion()));
        } catch (Exception e) {
            e.printStackTrace();
            hashMap.put("error", "修改失败:"+e.getMessage());
        }
        return JSON.toJSONString(hashMap);
    }

    @RequestMapping("/delete")
    public String delete() {
        HashMap<String,String> hashMap=new HashMap<>();
        String path="/nacl";
        String data="big";
        Integer version=1;
        try {
            client.delete().withVersion(version).forPath(path);
            hashMap.put("success", "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            hashMap.put("error", "删除失败:"+e.getMessage());
        }
        return JSON.toJSONString(hashMap);
    }


    @RequestMapping("/createAsyncZnode")
    public String createAsyncZnode(){
        String path = "/nacl";
        String data = "shuaige";
        try {
            client.create()
                    .creatingParentsIfNeeded()
                    .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                    //异步回调   增删改都有异步方法
                    .inBackground(new BackgroundCallback() {

                        @Override
                        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                            System.out.println("异步回调--获取权限:"+client.getACL().forPath(path));
                            System.out.println("异步回调--获取数据:"+new String(client.getData().forPath(path)));
                            System.out.println("异步回调--获取事件名称:"+event.getName());
                            System.out.println("异步回调--获取事件类型:"+event.getType());
                        }
                    })
                    .forPath(path, data.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            return "节点创建失败"+e.getMessage();
        }
        return "节点创建成功";
    }
}

到了这里,关于【SpringBoot】整合Zookeeper的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Zookeeper集成SpringBoot

    Curator 是 Apache ZooKeeper 的Java客户端库。 Zookeeper现有常见的Java API如:原生JavaAPI、Curator、ZkClient等。   pom.xml application.properties 一、建立连接 四个关键参数: 1、connectString 连接字符串 zkServer 地址和端口:\\\"192.168.253.128:2181\\\" 2、sessionTimeoutMs 会话超时时间,单位ms 3、connectionTimeo

    2024年02月11日
    浏览(28)
  • SpringBoot3集成Zookeeper

    标签:Zookeeper3.8 ,Curator5.5; ZooKeeper是一个集中的服务,用于维护配置信息、命名、提供分布式同步、提供组服务。分布式应用程序以某种形式使用所有这些类型的服务。 1、修改配置文件 2、服务启动 3、客户端测几个增删查的命令 Curator是一组Java库,它让ZooKeeper的使用变得

    2024年01月23日
    浏览(37)
  • SpringBoot整合Dubbo和Zookeeper分布式服务框架使用的入门项目实例

    Dubbo是一个 分布式服务框架 ,致力于提供高性能和透明化的RPC远程服务调用方案,以及SOA服务治理方案。简单的说,dubbo就是个服务框架,如果没有分布式的需求,其实是不需要用的,只有在分布式的时候,才有dubbo这样的分布式服务框架的需求。其本质上是个远程服务调用

    2024年01月21日
    浏览(36)
  • 2.Zookeeper集成springboot操作节点,事件监听,分布式锁实现

    1.Springboot项目中添加zookeeper 已经对应的客户端依赖 ,pom.xml文件如下 2.application.yml 文件中配置zookeeper连接的相关配置信息 3.java配置的方式添加zookeeper相关的配置 4.Zookeeper基础操作服务和分布式锁服务编码 5.watcher机制事件处理抽象封装 6.基本操作的单元测试代码

    2024年03月10日
    浏览(36)
  • Redis(发布订阅、事务、redis整合springboot、集成 Spring Cache)

    目录 一.redis的发布订阅 1、什么 是发布和订阅 2、Redis的发布和订阅 3、发布订阅的代码实现 二.Redis事务 1.事务简介 1、在事务执行之前 如果监听的key的值有变化就不能执行 2、在事务执行之前 如果监听的key的值没有变化就能执行 3、Exec之前就出现错误 4、Exec之后出现的错误

    2024年01月24日
    浏览(40)
  • DevOps系列文章 之 SpringBoot整合GitLab-CI实现持续集成

    在企业开发过程中,我们开发的功能或者是修复的BUG都需要部署到服务器上去,而这部分部署操作又是重复且繁琐的工作,GitLab-CI 持续集成为我们解决了这一痛点,将重复部署的工作自动化,大大的节省了程序员们的宝贵时间。本文详细讲述了 GitLab-CI 持续集成的安装、部署

    2024年02月13日
    浏览(35)
  • 【花艺电商】SpringBoot集成MyBatis-Plus、Swagger2、SpringSecurity、OAuth2等技术整合开发

    目录 一、功能介绍 1. 说明 2. 功能实现 3. 技术应用 二、技术详述 1.MyBatis-Plus 主要体现 项目应用 2.SpringSecurity 应用作用 三、页面展示 1. 登入 2. 主页 3. 详情 4. 购物车 5. 订单 6. 沙箱支付 每篇一获 这个项目主要使用了 Spring Security 、 MyBatis-Plus 、 Redis 、 雪花ID 、 参数校验技

    2024年01月25日
    浏览(37)
  • Springboot3.X整合Dubbo3.XSpringCloudAlibaba微服务 2022.0 + Springboot3.X 集成 Dubbo实现对外调用http内部调用RPC

    近期自己新开了一套SpringCloud Alibaba微服务项目,接口使用了对外HTTP,内部RPC的设计,具体点说就是外部用户或客户端通过Nginx访问到Gateway网关再分发到各个服务,内部各个服务之间统一使用Dubbo RPC进行通信。下面是Springboot3.x集成Dubbo的分享: 1. 需要的关键依赖 2. 启动程序入

    2024年02月15日
    浏览(26)
  • Spingboot整合Dubbo+zookeeper

    2023-12-26 19:38:05 最近学习分布式技术:Dubbo+zookeeper,准备写一个demo用springboot整合dubbo和zookeeper。但是看了网上一些教程都是几年前的,试着跟着写了几个demo没一个跑起来,基本是maven依赖方面的问题。 1、点击创建一个springboot项目 2、勾选web和lombok 3、创建 4、修改IDEA的Maven配置

    2024年02月04日
    浏览(35)
  • SpringCloud整合Zookeeper代替Eureka案例

    地址:https://github.com/13thm/study_springcloud/tree/main/days4 zookeeper是一个分布式协调工具,可以实现注册中心功能 关闭Linux服务器防火墙后启动zookeeper服务器 zookeeper服务器取代Eureka服务器,zk作为服务注册中心 下载地址:https://archive.apache.org/dist/zookeeper/ 1.解压zookeeper到/usr/local 2.改名

    2024年01月19日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包