java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot Zookeeper基本操作

SpringBoot集成Curator实现Zookeeper基本操作的代码示例

作者:Java毕设王

Zookeeper是一个Apache开源的分布式的应用,为系统架构提供协调服务,ZooKeeper的目标就是封装好复杂易出错的关键服务,将简单易用的接口和性能高效、功能稳定的系统提供给用户,本文给大家介绍了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);
        }
    }
}

以上就是SpringBoot集成Curator实现Zookeeper基本操作的代码示例的详细内容,更多关于SpringBoot Zookeeper基本操作的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文