zookeeper javaAPI
Maven dependency (ZooKeeper :3.5.5 corresponds to curator: 4.x)
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.0-1</version>
<scope>test</scope>
</dependency>
Copy the code
javaAPI
class Demo {
private val services = "localhost:2181,localhost:2182,localhost:2183"
/** * Create and obtain nodes */
@Test
fun createNode(a) {
// retry policy: the maximum number of retries is 3. Each retry interval is 1000ms
val exponentialBackoffRetry = ExponentialBackoffRetry(1000.3)
// Client creation: session timeout: 8000ms, connection timeout: 8000ms
val client = CuratorFrameworkFactory.newClient(services, 8000.8000, exponentialBackoffRetry)
// Start the client
client.start()
// Create a permanent sequence node c under /a/b, set the value to world, if the parent node does not exist, create a parent node
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/a/b/c"."ccc".toByteArray())
// Create a zero node hello under /a/b, set the value to world, if the parent node does not exist, create the parent node
client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/a/b/hello"."world".toByteArray())
// Get data
println(client.data.forPath("/a/b/hello").toString(StandardCharsets.UTF_8))
// Close the client (temporary nodes will be deleted)
client.close();
}
/** * watch */
@Test
fun watch(a) {
// retry policy: the maximum number of retries is 3. Each retry interval is 1000ms
val exponentialBackoffRetry = ExponentialBackoffRetry(1000.3)
// Client creation: session timeout: 8000ms, connection timeout: 8000ms
val client = CuratorFrameworkFactory.newClient(services, 8000.8000, exponentialBackoffRetry)
// Start the client
client.start()
// Bind the listener node (can listen on nodes that do not exist)
val treeCache = TreeCache(client, "/watch").apply {
listenable.addListener(TreeCacheListener { curatorFramework, treeCacheEvent ->
TreeCacheEvent{type=INITIALIZED, data=null}
if (treeCacheEvent.data= =null) return@TreeCacheListener
println(treeCacheEvent)
})
}.also { it.start() }
/ / create
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/watch"."ccc".toByteArray())
// Create a child node
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/watch/a"."aaa".toByteArray())
/ / modify
client.setData().forPath("/watch"."cc".toByteArray())
// Modify the child node
client.setData().forPath("/watch/a"."aa".toByteArray())
// Delete the child node
client.delete().forPath("/watch/a")
// Delete the parent node if the child node is empty.
client.delete().forPath("/watch")
Thread.sleep(3000) client.close(); }}Copy the code