SpringBoot集成Curator實現(xiàn)Zookeeper基本操作的代碼示例
Zookeeper是一個Apache開源的分布式的應用,為系統(tǒng)架構提供協(xié)調服務。從設計模式角度來審視:該組件是一個基于觀察者模式設計的框架,負責存儲和管理數(shù)據(jù),接受觀察者的注冊,一旦數(shù)據(jù)的狀態(tài)發(fā)生變化,Zookeeper就將負責通知已經(jīng)在Zookeeper上注冊的觀察者做出相應的反應,從而實現(xiàn)集群中類似Master/Slave管理模式。ZooKeeper的目標就是封裝好復雜易出錯的關鍵服務,將簡單易用的接口和性能高效、功能穩(wěn)定的系統(tǒng)提供給用戶。

zookeeper安裝單機模式
http://www.javacui.com/opensource/445.html
官網(wǎng)
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 # 重試次數(shù) 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;
}
公用連接創(chuàng)建對象
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()));
}
}
編寫測試類,實現(xiàn)各種基礎操作,并挨個測試
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());
}
// 創(chuàng)建節(jié)點
@Test
void createPath() throws Exception{
CuratorFramework client= zk.curatorFramework();
// 父節(jié)點不存在則創(chuàng)建
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));
}
// 賦值,修改數(shù)據(jù)
@Test
void setData() throws Exception{
CuratorFramework client = zk.curatorFramework();
int version = 0; // 當前節(jié)點的版本信息
Stat stat = new Stat();
client.getData().storingStatIn(stat).forPath("/javacui/p1");
version = stat.getVersion();
// 如果版本信息不一致,說明當前數(shù)據(jù)被修改過,則修改失敗程序報錯
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));
}
// 查詢節(jié)點
@Test
void getPath() throws Exception{
CuratorFramework client= zk.curatorFramework();
// 查內容
byte[] data = client.getData().forPath("/javacui/p1");
System.out.println(new String(data));
// 查狀態(tài)
Stat stat = new Stat();
client.getData().storingStatIn(stat).forPath("/javacui/p1");
System.out.println(JSON.toJSONString(stat, true));
}
// 刪除節(jié)點
@Test
void deletePath() throws Exception{
CuratorFramework client= zk.curatorFramework();
// deletingChildrenIfNeeded如果有子節(jié)點一并刪除
// guaranteed必須成功比如網(wǎng)絡抖動時造成命令失敗
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");
}
// 查詢子節(jié)點
@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實現(xiàn)Zookeeper基本操作的代碼示例的詳細內容,更多關于SpringBoot Zookeeper基本操作的資料請關注腳本之家其它相關文章!
相關文章
Java實現(xiàn)文件壓縮與解壓的示例[zip格式,gzip格式]
本篇文章主要介紹了Java實現(xiàn)文件壓縮與解壓的示例[zip格式,gzip格式],具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-01-01
Springboot整合MongoDB進行CRUD操作的兩種方式(實例代碼詳解)
這篇文章主要介紹了Springboot整合MongoDB進行CRUD操作的兩種方式,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04
JAVA 格式化JSON數(shù)據(jù)并保存到json文件中的實例
這篇文章主要介紹了JAVA 格式化JSON數(shù)據(jù)并保存到json文件中的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
spring boot使用thymeleaf為模板的基本步驟介紹
Spring Boot項目的默認模板引擎是Thymeleaf,這沒什么好說的,個人覺得也非常好,下面這篇文章主要給大家介紹了關于spring boot使用thymeleaf為模板的相關資料,需要的朋友可以參考借鑒,下面來一起學習學習吧。2018-01-01

