java 使用 curator 的 API 操作 zookeeper
依赖
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
public class TestCuratorService {
private String zookeeperConnectionString = "127.0.0.1:2181";
private CuratorFramework client;
/**
* 连接初始化
* 方式一
*/
@Before
public void initClient1() {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy);
client.start();
}
/**
* 连接初始化
* 方式二
*/
public void initClient2() {
ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 3);
client = CuratorFrameworkFactory.builder()
//zookeeper 的连接地址
.connectString(zookeeperConnectionString)
.connectionTimeoutMs(10000)
.sessionTimeoutMs(10000)
.retryPolicy(retry).build();
client.start();
}
@Test
public void dataIsExists() throws Exception {
String path = "/test/aaaa";
Stat stat = client.checkExists()
.usingWatcher(new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println("监听回调");
}
})
.forPath(path);
System.out.println(stat);
}
@Test
public void createPath() throws Exception {
String path = "/test/aaaa";
String res = client.create()
// 递归创建path
.creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
.forPath(path, "path数据内容".getBytes());
System.out.println(res);
}
@Test
public void deletePath() throws Exception {
String path = "/test/aaaa";
client.delete()
// 强制删除
.guaranteed()
// 递归删除
.deletingChildrenIfNeeded()
//.withVersion(-1)
.forPath(path);
}
@Test
public void getPath() throws Exception {
String path = "/test";
CountDownLatch countDownLatch = new CountDownLatch(1);
List<String> childPaths = client.getChildren()
.usingWatcher(new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println("监听回调");
}
})
// inBackground会导致forPath的返回为null
.inBackground(new BackgroundCallback() {
@Override
public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) {
System.out.println("异步操作");
List<String> pathList = curatorFramework.getChildren().forPath(path);
System.out.println(pathList);
countDownLatch.countDown();
}
})
.forPath(path);
countDownLatch.await();
}
@Test
public void getData() throws Exception {
String path = "/test";
byte[] bytes = client.getData()
.usingWatcher(new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println("监听回调");
}
})
/*
// inBackground会导致forPath的返回为null
.inBackground(new BackgroundCallback() {
@Override
public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) {
System.out.println("异步操作");
}
})
*/
.forPath(path);
String data = new String(bytes);
System.out.println(data);
}
@Test
public void updateData() throws Exception {
String path = "/test";
client.setData().forPath(path, "数据内容".getBytes());
}
/**
* 事务操作
*/
@Test
public void transaction() throws Exception {
//创建事务
CuratorOp curatorOp = client.transactionOp().delete().forPath("/test/aaa");
//执行事务
List<CuratorTransactionResult> results = client.transaction().forOperations(curatorOp);
}
/**
* 分布式锁
*/
@Test
public void zookeeperLock() throws Exception {
String lockPath = "/test/lock";
InterProcessMutex lock = new InterProcessMutex(client, lockPath);
// 加锁
if (lock.acquire(5, TimeUnit.SECONDS)) {
try {
// 业务操作
} finally {
// 解锁
lock.release();
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!