SpringBoot集成Curator实现Zookeeper基本操作

系列文章目录



前言

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看懂了就去分享给你的码吧。
在这里插入图片描述


Zookeeper是一个Apache开源的分布式的应用,为系统架构提供协调服务。从设计模式角度来审视:该组件是一个基于观察者模式设计的框架,负责存储和管理数据,接受观察者的注册,一旦数据的状态发生变化,Zookeeper就将负责通知已经在Zookeeper上注册的观察者做出相应的反应,从而实现集群中类似Master/Slave管理模式。ZooKeeper的目标就是封装好复杂易出错的关键服务,将简单易用的接口和性能高效、功能稳定的系统提供给用户。
在这里插入图片描述
zookeeper安装单机模式

http://www.javacui.com/opensource/445.html

官网

https://curator.apache.org/releases.html#Current_Release

POM引入

<!--                      curator                      -->
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>5.2.0</version>
</dependency>
<!--                      fastjson                      -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.79</version>
</dependency>

application.yml定义连接属性

server:
  port: 80
curator:
  connectString: 192.168.3.22:2181 # zookeeper 地址
  retryCount: 1 # 重试次数
  elapsedTimeMs: 2000 # 重试间隔时间
  sessionTimeoutMs: 60000 # session超时时间
  connectionTimeoutMs: 10000 # 连接超时时间

使用Springboot配置读取

package com.example.springboot.config;
 
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
 
/**
 * @Auther: Java小强
 * @Date: 2022/2/4 - 19:37
 * @Decsription: com.example.springboot.config
 * @Version: 1.0
 */
@Data
@Component
@ConfigurationProperties(prefix = "curator")
public class CuratorConf {
    private int retryCount;
    private int elapsedTimeMs;
    private String connectString;
    private int sessionTimeoutMs;
    private int connectionTimeoutMs;
}

公用连接创建对象

package com.example.springboot.tool;
 
import com.example.springboot.config.CuratorConf;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
/**
 * @Auther: Java小强
 * @Date: 2022/2/4 - 19:37
 * @Decsription: com.example.springboot.tool
 * @Version: 1.0
 */
@Configuration
public class ZkConfiguration {
 
    @Autowired
    private CuratorConf curatorConf;
 
    /**
     * 这里会自动调用一次start,请勿重复调用
     */
    @Bean(initMethod = "start")
    public CuratorFramework curatorFramework() {
        return CuratorFrameworkFactory.newClient(
                curatorConf.getConnectString(),
                curatorConf.getSessionTimeoutMs(),
                curatorConf.getConnectionTimeoutMs(),
                new RetryNTimes(curatorConf.getRetryCount(), curatorConf.getElapsedTimeMs()));
    }
 
}

编写测试类,实现各种基础操作,并挨个测试

package com.example.springboot;
 
import com.alibaba.fastjson.JSON;
import com.example.springboot.tool.ZkConfiguration;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.zookeeper.data.Stat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
 
import java.nio.charset.StandardCharsets;
import java.util.List;
 
/**
 * @Auther: Java小强
 * @Date: 2022/2/4 - 19:33
 * @Decsription: com.example.springboot
 * @Version: 1.0
 */
@SpringBootTest(classes = Application.class)
public class CuratorTest {
    @Autowired
    private ZkConfiguration zk;
 
    // 测试连接
    @Test
    void contextLoads() {
        CuratorFramework client= zk.curatorFramework();
        System.out.println(client.toString());
    }
 
    // 创建节点
    @Test
    void createPath() throws Exception{
        CuratorFramework client= zk.curatorFramework();
        // 父节点不存在则创建
        String path = client.create().creatingParentsIfNeeded().forPath("/javacui/p1" ,
                "Java小强博客".getBytes(StandardCharsets.UTF_8));
        System.out.println(path);
        byte[] data = client.getData().forPath("/javacui/p1");
        System.out.println(new String(data));
    }
 
    // 赋值,修改数据
    @Test
    void setData() throws Exception{
        CuratorFramework client = zk.curatorFramework();
 
        int version = 0; // 当前节点的版本信息
        Stat stat = new Stat();
        client.getData().storingStatIn(stat).forPath("/javacui/p1");
        version = stat.getVersion();
        // 如果版本信息不一致,说明当前数据被修改过,则修改失败程序报错
        client.setData().withVersion(version).forPath("/javacui/p1",
                "Java崔的博客".getBytes(StandardCharsets.UTF_8));
        byte[] data = client.getData().forPath("/javacui/p1");
        System.out.println(new String(data));
    }
 
    // 查询节点
    @Test
    void getPath() throws Exception{
        CuratorFramework client= zk.curatorFramework();
        // 查内容
        byte[] data = client.getData().forPath("/javacui/p1");
        System.out.println(new String(data));
 
        // 查状态
        Stat stat = new Stat();
        client.getData().storingStatIn(stat).forPath("/javacui/p1");
        System.out.println(JSON.toJSONString(stat, true));
    }
 
    // 删除节点
    @Test
    void deletePath() throws Exception{
        CuratorFramework client= zk.curatorFramework();
        // deletingChildrenIfNeeded如果有子节点一并删除
        // guaranteed必须成功比如网络抖动时造成命令失败
        client.delete().guaranteed().deletingChildrenIfNeeded().inBackground(new BackgroundCallback() {
            @Override
            public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
                System.out.println("删除成功");
                // { "path":"/javacui/p1","resultCode":0,"type":"DELETE"}
                System.out.println(JSON.toJSONString(curatorEvent, true));
            }
        }).forPath("/javacui/p1");
    }
 
    // 查询子节点
    @Test
    void getPaths() throws Exception{
        CuratorFramework client= zk.curatorFramework();
        List<String> paths = client.getChildren().forPath("/javacui");
        for(String p : paths){
            System.out.println(p);
        }
    }
}
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Curator是一个ZooKeeper客户端库,用于简化ZooKeeper API的使用。Spring Boot是一个非常流行的Java应用程序框架。将它们结合起来,可以使开发人员更轻松地使用ZooKeeper实现分布式应用程序。 以下是Spring Boot整合Curator的步骤: 1. 添加Curator依赖 在`pom.xml`文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-framework</artifactId> <version>4.2.0</version> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>4.2.0</version> </dependency> ``` 2. 配置ZooKeeper连接 在`application.yml`文件中添加以下配置: ```yaml zookeeper: connectString: 127.0.0.1:2181 namespace: myapp ``` 3. 创建Curator客户端 在Spring Boot应用程序中创建Curator客户端,例如: ```java @Configuration public class ZookeeperConfig { @Autowired private ZookeeperProperties properties; @Bean public CuratorFramework curatorFramework() { String connectString = properties.getConnectString(); String namespace = properties.getNamespace(); CuratorFramework curatorFramework = CuratorFrameworkFactory.builder() .connectString(connectString) .namespace(namespace) .retryPolicy(new ExponentialBackoffRetry(1000, 3)) .build(); curatorFramework.start(); return curatorFramework; } } ``` 4. 使用Curator客户端 使用Curator客户端实现ZooKeeper的常用操作,例如: ```java @Autowired private CuratorFramework curatorFramework; public void createNode(String path, byte[] data) throws Exception { curatorFramework.create().creatingParentsIfNeeded().forPath(path, data); } public void deleteNode(String path) throws Exception { curatorFramework.delete().deletingChildrenIfNeeded().forPath(path); } public byte[] getData(String path) throws Exception { return curatorFramework.getData().forPath(path); } public void setData(String path, byte[] data) throws Exception { curatorFramework.setData().forPath(path, data); } public List<String> getChildren(String path) throws Exception { return curatorFramework.getChildren().forPath(path); } ``` 这些步骤可以让你方便地使用Curator作为ZooKeeper客户端库来实现分布式应用程序。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java毕设王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值