当前位置: 代码网 > it编程>编程语言>Java > SpringBoot集成Curator实现Zookeeper基本操作的代码示例

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

2024年05月26日 Java 我要评论
zookeeper是一个apache开源的分布式的应用,为系统架构提供协调服务。从设计模式角度来审视:该组件是一个基于观察者模式设计的框架,负责存储和管理数据,接受观察者的注册,一旦数据的状态发生变化

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基本操作的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com