摘要:无。
环境
Windows 10 企业版 LTSC 21H2
Java 1.8
Maven 3.6.3
Spring 5.3.31
Spring Boot 2.7.18
ZooKeeper 3.8.4
Curator 5.7.1
1 入门案例
1.1 创建项目
目录结构:
code1 2 3 4 5 6 7 8 9 10 11
| demo-curator/ ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── com/ │ │ │ └── example/ │ │ │ └── DemoApplication.java │ │ └── resources/ │ │ └── application.yml │ └── test/ └── pom.xml
|
1.2 管理依赖
创建pom.xml文件:
pom.xml1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.18</version> <relativePath/> </parent>
<groupId>com.example</groupId> <artifactId>demo-curator</artifactId> <version>1.0.0-SNAPSHOT</version>
<properties> <java.version>1.8</java.version> </properties>
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>5.7.1</version> </dependency> </dependencies>
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
|
1.3 运行代码
在启动类中实现CommandLineRunner接口,在应用启动后测试:
java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| @SpringBootApplication public class DemoApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }
@Override public void run(String... args) throws Exception { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy); client.start();
client.create() .withMode(CreateMode.PERSISTENT) .forPath("/user/zs", "张三".getBytes()); client.create() .withMode(CreateMode.EPHEMERAL) .forPath("/user/ls", "李四".getBytes());
byte[] zs = client.getData().forPath("/user/zs"); byte[] ls = client.getData().forPath("/user/ls"); System.out.println("节点数据:" + new String(zs)); System.out.println("节点数据:" + new String(ls));
client.close(); } }
|
2 核心组件
核心组件:
- CuratorFrameworkFactory:客户端工厂类,用于创建CuratorFramework实例,支持多种配置方式。
- CuratorFramework:Curator的客户端入口,所有操作通过它发起,封装了ZooKeeper的常用操作。
- RetryPolicy:重试策略接口,定义重试的条件和间隔,常用实现有ExponentialBackoffRetry。
- CreateMode:节点创建模式,支持创建四种节点。
- ConnectionState:连接状态枚举。
条