Zookeeper集成SpringBoot

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

Curator 是 Apache ZooKeeper 的Java客户端库。
Zookeeper现有常见的Java API如:原生JavaAPI、Curator、ZkClient等。

 

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.9</version>
        <relativePath/>
    </parent>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>

        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.9.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>5.2.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>5.2.1</version>
        </dependency>




    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <releases>
                <enabled>false</enabled>
            </releases>
        </pluginRepository>
    </pluginRepositories>

</project>

application.properties

server.port= 8085

zookeeper.host= localhost:2181

一、建立连接

四个关键参数:
1、connectString 连接字符串 zkServer 地址和端口:"192.168.253.128:2181"
2、sessionTimeoutMs 会话超时时间,单位ms
3、connectionTimeoutMs 连接超时时间,单位ms
4、retryPolicy 重试策略

ZookeeperConfig
package com.example.demo.zk.config;
 
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
/**
 * @author yanqiuxiang
 * @version 1.0
 */
@Configuration
public class ZookeeperConfig {
    @Value("${zookeeper.host}")
    private String host;
 
    @Bean
    public CuratorFramework curatorFramework() {
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(host)
                .sessionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(500, 5))
                .build();
        curatorFramework.start();
 
        return curatorFramework;
    }
 
}
ZookeeperController

二、创建节点:create 持久 临时 顺序 数据
  1. 基本创建 :create().forPath("")
  2. 创建节点 带有数据:create().forPath("",data)
  3. 设置节点的类型:create().withMode().forPath("",data)
  4. 创建多级节点  /app1/p1 :create().creatingParentsIfNeeded().forPath("",data)文章来源地址https://www.toymoban.com/news/detail-676871.html

package com.example.demo.zk.controller;
 

import com.example.demo.zk.JsonResult;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
 
import java.nio.charset.StandardCharsets;
import java.util.List;
 
/**
 * @author yanqiuxiang
 * @version 1.0
 */
@RestController
@RequestMapping(path = "/zookeeper", produces = "application/json;charset=utf-8")
public class ZookeeperController {
    private final CuratorFramework curatorFramework;
 
    @Autowired
    public ZookeeperController(CuratorFramework curatorFramework) {
        this.curatorFramework = curatorFramework;
    }
 
    /**
     * 判断znode是否存在
     * @param node 节点名称
     */
    @RequestMapping(value = "/exist", method = RequestMethod.GET)
    public JsonResult<Stat> exist(String node) throws Exception {
        Stat stat = curatorFramework.checkExists().forPath(node);
 
        return new JsonResult(200, stat);
    }
 
    /**
     * 创建一个znode
     * @param node 节点名称
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public JsonResult<Void> create(String node) throws Exception {
        curatorFramework.create()
                .creatingParentContainersIfNeeded()
                /*
                创建模式:常用的有
                    PERSISTENT:持久化节点,客户端与zookeeper断开连接后,该节点依旧存在,只要不手动删除,该节点就会永远存在。
                    PERSISTENT_SEQUENTIAL:持久化顺序编号目录节点,客户端与zookeeper断开连接后,该节点依旧存在,只是zookeeper给该节点名称进行顺序编号。
                    EPHEMERAL:临时目录节点,客户端与zookeeper断开连接后,该节点被删除。
                    EPHEMERAL_SEQUENTIAL:临时顺序编号目录节点,客户端与zookeeper断开连接后,该节点被删除,只是zookeeper给该节点名称进行顺序编号。
                */
                .withMode(CreateMode.EPHEMERAL)
                .forPath(node);
 
        return new JsonResult("创建成功");
    }
 
    /**
     * 设置znode节点的数据
     * @param node 节点名称
     * @param data 节点的数据
     */
    @RequestMapping(value = "/setData", method = RequestMethod.GET)
    public JsonResult<Void> setData(String node, String data) throws Exception {
        curatorFramework.setData().forPath(node, data.getBytes(StandardCharsets.UTF_8));
 
        return new JsonResult("设置成功");
    }
 
    /**
     * 删除节点
     * @param node 节点名称
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public JsonResult<Void> delete(String node) throws Exception {
        curatorFramework.delete().forPath(node);
 
        return new JsonResult("删除成功");
    }
 
    /**
     * 删除节点及其子节点的数据
     * @param node 节点名称
     */
    @RequestMapping(value = "/deleteDeeply", method = RequestMethod.GET)
    public JsonResult<Void> deleteDeeply(String node) throws Exception {
        curatorFramework.delete().deletingChildrenIfNeeded().forPath(node);
 
        return new JsonResult("删除成功");
    }
 
    /**
     * 获取节点的数据
     * @param node 节点名称
     */
    @RequestMapping(value = "/getData", method = RequestMethod.GET)
    public JsonResult<String> getData(String node) throws Exception {
        byte[] bytes = curatorFramework.getData().forPath(node);
 
        return new JsonResult(200, new String(bytes));
    }
 
    /**
     * 获取当前节点的子节点数据
     * @param node 节点名称
     */
    @RequestMapping(value = "/getChildren", method = RequestMethod.GET)
    public JsonResult<List<String>> getChildren(String node) throws Exception {
        List<String> list = curatorFramework.getChildren().forPath(node);
 
        return new JsonResult(200, list);
    }
 
}
JsonResult
package com.example.demo.zk;

import java.io.Serializable;
/**
 * 用于封装服务器到客户端的Json返回值
 * @author yanqiuxiang
 *
 */
public class JsonResult<T> implements Serializable {
    //Serializable将对象的状态保存在存储媒体中以便可以在以后重新创建出完全相同的副本
    public static final int SUCCESS=0;
    public static final int ERROR=1;
    public static final int OTHER=2;

    private int state;
    private String message = "";
    private T data;
    private String pass="";

    public JsonResult(){
        state = SUCCESS;
    }
    //为了方便,重载n个构造器
    public JsonResult(int state, String message, T data) {
        super();
        this.state = state;
        this.message = message;
        this.data = data;
    }
    public JsonResult(int state,String error){
        this(state,error,null);
    }
    public JsonResult(int state,T data){
        this(state,"",data);
    }
    public JsonResult(String error){
        this(ERROR,error,null);
    }

    public JsonResult(T data){
        this(SUCCESS,"",data);
    }
    public JsonResult(int state){
        this(state,"",null);
    }
    public JsonResult(Throwable e){
        this(ERROR,e.getMessage(),null);
    }
    public int getState() {
        return state;
    }
    public void setState(int state) {
        this.state = state;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public T getData() {
        return data;
    }
    public void setData(T data) {
        this.data = data;
    }
    public static int getSuccess() {
        return SUCCESS;
    }
    public static int getError() {
        return ERROR;
    }
    @Override
    public String toString() {
        return "JsonResult [state=" + state + ", message=" + message + ", pass=" + pass + ", data=" + data + "]";
    }
}

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

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

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

相关文章

  • SpringBoot~ dubbo + zookeeper实现分布式开发的应用

    配置服务名字, 注册中心地址, 扫描被注册的包 server.port=8081 #当前应用名字 dubbo.application.name=provider-server #注册中心地址 dubbo.registry.address=zookeeper://127.0.0.1:2181 #扫描指定包下服务 dubbo.scan.base-packages=com.demo.service 实现一个接口,在接口中完成需求 public interface Translate { String tran

    2024年04月10日
    浏览(42)
  • SpringBoot集成Skywalking实现分布式链路追踪

    官方网址:  Apache SkyWalking 官方文档:  SkyWalking 极简入门 | Apache SkyWalking 下载地址 :Downloads | Apache SkyWalking  Agent :以探针的方式进行请求链路的数据采集,并向管理服务上报; OAP-Service :接收数据,完成数据的存储和展示; Storage :数据的存储层,支持ElasticSearch、Mysql、

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

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

    2024年01月21日
    浏览(36)
  • 分布式id生成方案及springboot进行集成

    UUID(Universally Unique Identifier) 即通用唯一识别码,是一种由网络软件使用的标识符,它是由IP地址、当前时间戳、随机数、节点等多个部分组成,具有唯一性。但是,UUID方案的缺点是,生成的id较长,不便于存储和使用。 Snowflake算法 它是Twitter公司开源的一个分布式唯一ID生成器

    2023年04月08日
    浏览(29)
  • springboot dubbo seata nacos集成 分布式事务seata实现

    官网:http://seata.io/zh-cn/docs/overview/what-is-seata.html Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式,为用户打造一站式的分布式解决方案。 官网;https://cn.dubbo.apache.org/zh-cn/overview/what/

    2024年02月13日
    浏览(37)
  • 【SpringBoot应用篇】SpringBoot集成atomikos实现多数据源配置和分布式事务管理

    讨论分布式事务之前我们分清两个概念: 本地事务 、 分布式事务 ; 本地事务是解决 单个数据源 上的数据操作的 一致性 问题的话,而分布式事务则是为了解决 跨越多个数据源 上数据操作的 一致性 问题。 百度官方对分布式事务的定义是指事务的参与者、支持事务的服务

    2024年02月16日
    浏览(41)
  • 分布式锁解决方案_Zookeeper实现分布式锁

    提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加 分布式锁解决方案_Zookeeper实现分布式锁 提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档 提示:这里可以添加本文要记录的大概内容: Zookeeper 是一个开源的分布式协调服务,它

    2024年02月03日
    浏览(30)
  • 分布式调用与高并发处理 Zookeeper分布式协调服务

    单机架构 一个系统业务量很小的时候所有的代码都放在一个项目中就好了,然后这个项目部署在一台服务器上,整个项目所有的服务都由这台服务器提供。 缺点: 服务性能存在瓶颈,用户增长的时候性能下降等。 不可伸缩性 代码量庞大,系统臃肿,牵一发动全身 单点故障

    2024年02月12日
    浏览(48)
  • 【分布式】Zookeeper

    可以参考:https://zhuanlan.zhihu.com/p/62526102 ZooKeeper 是一个分布式的,开放源码的分布式应用程序协同服务。ZooKeeper 的设计目标是将那些复杂且容易出错的分布式一致性服务封装起来,构成一个高效可靠的原语集,并以一系列简单易用的接口提供给用户使用。 配置管理。 Java微服

    2024年02月11日
    浏览(35)
  • 分布式服务框架_Zookeeper--管理分布式环境中的数据

    安装和配置详解 本文介绍的 Zookeeper 是以 3.2.2 这个稳定版本为基础,最新的版本可以通过官网   http://hadoop.apache.org/zookeeper/ 来获取, Zookeeper 的安装非常简单,下面将从单机模式和集群模式两个方面介绍 Zookeeper 的安装和配置。 单机模式

    2024年02月12日
    浏览(31)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包