Maven Dependencies
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.8.0</version>
</dependency>
Path Cache
The Path cache is used to monitor a znode child node. When a child node is added, updated, and deleted, the Path cache changes its state and contains the latest child nodes, the data and the state of the child nodes. (note here that he listens to only one level of child nodes and does not loop over the child under the subnodes)
The actual use will involve four classes:
Pathchildrencache
Pathchildrencacheevent
Pathchildrencachelistener
Childdata
Create Path Cache
Create the path Cache by using the following constructor:
Public Pathchildrencache (curatorframework client, String path, Boolean cachedata, Boolean dataiscompressed, Final Executorservice Executorservice)
To use cache, you must call its Start method without having to call the Close method later.
There are two start, one of which can be passed into the StartMode to set the warm-up mode for the initial cache (warm):
Personally, it is recommended that you use this construction method to executorservice your own thread pool to ensure that the threads are controllable
Add Monitor node status
When adding listener that monitor node state changes, we recommend using this method to manually pass in our constructed thread pool to ensure that the thread is controllable.
Childrencache.getlistenable (). (T Listener, Executor Executor);
Why do you have to pass the thread pool yourself? Look at the map and the source code
Public Pathchildrencache (curatorframework client, String path, Boolean cachedata)
{
This (client, path, CacheData, False, new Closeableexecutorservice (Executors.newsinglethreadexecutor) ( Defaultthreadfactory), true);
}
public void AddListener (T listener)
{
AddListener (Listener, Moreexecutors.samethreadexecutor ());
}
Because the ZK loses the link, the default does not pass the thread pool method, each time the connection will be new to a thread pool, threads have been active, if the ZK service end of a long time failed to recover, will cause the client ready to fill
Set/update, remove
Setup/Update, remove is actually using the client (curatorframework) to operate, not through the Pathchildrencache operation:
Client.setdata (). Forpath (path, bytes);
Client.create (). creatingparentsifneeded (). Forpath (path, bytes);
Client.delete (). Forpath (path);
The query cache uses the following method:
For (Childdata Data:cache.getCurrentData ()) {
System.out.println (Data.getpath () + "=" + New String (Data.getdata ()));
}
Finally attach a complete code
Import Java.util.concurrent.CountDownLatch;
Import Java.util.concurrent.LinkedBlockingQueue;
Import Java.util.concurrent.ThreadPoolExecutor;
Import Java.util.concurrent.TimeUnit;
Import Org.apache.curator.framework.CuratorFramework;
Import Org.apache.curator.framework.CuratorFrameworkFactory;
Import Org.apache.curator.framework.recipes.cache.PathChildrenCache;
Import Org.apache.curator.retry.ExponentialBackoffRetry;
/**
* Zkclient
*
* @author Jiangzhixiong
* @email xingxuan_jzx@foxmail.com
* @date October 12, 2015 5:18:21
*/
public class Childpathzkclient {
IP and Port URLs
Private String URL;
Base path that requires listening
Private String BasePath;
private static Curatorframework client = NULL;
Private final static Threadpoolexecutor executor = new Threadpoolexecutor (5l, timeunit.seconds, new Linkedblockin Gqueue<runnable> (m), New Threadpoolexecutor.callerrunspolicy ());
public void Init () throws Throwable {
if (BasePath = = null) {
BasePath = "O2o/zk/cache";
}
Client = Curatorframeworkfactory.builder (). namespace (BasePath). ConnectString (URL). SESSIONTIMEOUTMS (5000). CONNECTIONTIMEOUTMS (3000). Retrypolicy (New Exponentialbackoffretry (1000, 0)). Build ();
Client.start ();
/**
* Monitor the changes of child nodes
*/
Watchchild ("/");
}
protected static void Watchchild (String path) throws Exception {
Pathchildrencache Childrencache = new Pathchildrencache (client, path, True, false, executor);
Zkpathlistener listener = new Zkpathlistener ();
Listener.setpathchildrencache (Childrencache);
Childrencache.getlistenable (). AddListener (Listener, executor);
Childrencache.start ();
}
Public String GetUrl () {
return URL;
}
public void SetUrl (String URL) {
This.url = URL;
}
Public String Getbasepath () {
return basepath;
}
public void Setbasepath (String basepath) {
This.basepath = BasePath;
}
public static void Main (string[] args) throws Throwable {
Countdownlatch latch = new Countdownlatch (1);
Client = Curatorframeworkfactory.builder (). Namespace ("O2o/zk/cache"). ConnectString ("192.168.200.98:2181"). SESSIONTIMEOUTMS (5000). CONNECTIONTIMEOUTMS (3000)
. Retrypolicy (New Exponentialbackoffretry (1000, 3)). Build ();
Client.start ();
/**
* Monitor the changes of child nodes
*/
Watchchild ("/");
Latch.await ();
}
}
Import Java.util.Map;
Import Org.apache.commons.lang3.StringUtils;
Import Org.apache.curator.framework.CuratorFramework;
Import Org.apache.curator.framework.recipes.cache.PathChildrenCache;
Import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
Import Org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
Import Org.apache.logging.log4j.Level;
Import Org.apache.logging.log4j.LogManager;
Import Org.apache.logging.log4j.Logger;
Import Org.apache.logging.log4j.core.LoggerContext;
Import org.apache.logging.log4j.core.config.Configuration;
Import Org.apache.logging.log4j.core.config.LoggerConfig;
Import Com.jd.o2o.web.product.constants.zk.ZkSwitchEnum;
Import Com.jd.o2o.web.product.constants.zk.ZkValueEnum;
Import Com.jd.o2o.zk.cache.serializer.ZooKeeperSerializer;
Import Com.jd.o2o.zk.cache.serializer.impl.JdkSerializationZooKeeperSerializer;
/**
* ZK Listener
*
* @author Jiangzhixiong
* @email xingxuan_jzx@foxmail.com
* @date October 12, 2015 5:18:38
*/
public class Zkpathlistener implements Pathchildrencachelistener {
Private final Logger Logger = Logmanager.getlogger (Zkpathlistener. Class);
Private final zookeeperserializer<?> Defaultserializer = new Jdkserializationzookeeperserializer ();
Private Pathchildrencache Pathchildrencache;
@Override
public void Childevent (Curatorframework paramcuratorframework, Pathchildrencacheevent event) throws Exception {
Switch (Event.gettype ()) {
Case child_added:
Todo
System.out.println (Defaultserializer.deserialize (Event.getdata (). GetData ()));
Break
Case child_updated:
Todo
System.out.println (Defaultserializer.deserialize (Event.getdata (). GetData ()));
Break
Case child_removed:
Todo
System.out.println (Defaultserializer.deserialize (Event.getdata (). GetData ()));
Break
Default
Break
}
}
}
Node Cache
Node cache is used to monitor a znode. When a node's data is modified or deleted, node cache can update its state to include the latest changes.
The following three classes are involved:
Nodecache
Nodecachelistener
Childdata
Building Nodecache
Public Nodecache (curatorframework client, String Path)
To use the cache, still call its Start method without having to call the Close method.
Add Monitor node status
When adding listener that monitor node state changes, we recommend using this method to manually pass in our constructed thread pool to ensure that the thread is controllable.
Nodecache.getlistenable (). (T Listener, Executor Executor);
Also attach a complete code
Import Java.util.concurrent.CountDownLatch;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Org.apache.curator.framework.CuratorFramework;
Import Org.apache.curator.framework.CuratorFrameworkFactory;
Import Org.apache.curator.framework.recipes.cache.NodeCache;
Import Org.apache.curator.framework.recipes.cache.NodeCacheListener;
Import Org.apache.curator.retry.ExponentialBackoffRetry;
/**
* ZK Link
*
* @author Jiangzhixiong
* @email xingxuan_jzx@foxmail.com
* @date October 12, 2015 5:18:21
*/
public class Zknodeclient {
IP and Port URLs
Private String URL;
Base path that requires listening
Private String BasePath;
private static Nodecache Nodecache;
private static Curatorframework client = NULL;
Private final static Executorservice Executor_service = Executors.newsinglethreadexecutor ();
public void Init () throws Throwable {
if (BasePath = = null) {
BasePath = "O2o/zk/cache";
}
Client = Curatorframeworkfactory.builder (). namespace (BasePath). ConnectString (URL). SESSIONTIMEOUTMS (5000). CONNECTIONTIMEOUTMS (3000). Retrypolicy (New Exponentialbackoffretry (1000, 0)). Build ();
Client.start ();
Nodecache = new Nodecache (client, "/");
/**
* Monitor the changes of child nodes
*/
Watchchild ();
}
protected static void Watchchild () throws Exception {
Nodecache.getlistenable (). AddListener (New Nodecachelistener () {
@Override
public void NodeChanged () throws Exception {
System.out.println (Nodecache.getcurrentdata (). GetPath () + ":" + nodecache.getcurrentdata (). GetData ());
}
}, Executor_service);
Nodecache.start ();
}
Public String GetUrl () {
return URL;
}
public void SetUrl (String URL) {
This.url = URL;
}
Public String Getbasepath () {
return basepath;
}
public void Setbasepath (String basepath) {
This.basepath = BasePath;
}
public static void Main (string[] args) throws Throwable {
Countdownlatch latch = new Countdownlatch (1);
Client = Curatorframeworkfactory.builder (). Namespace ("O2o/zk/cache"). ConnectString ("192.168.200.98:2181"). SESSIONTIMEOUTMS (5000). CONNECTIONTIMEOUTMS (3000)
. Retrypolicy (New Exponentialbackoffretry (1000, 3)). Build ();
Client.start ();
/**
* Monitor the changes of child nodes
*/
Watchchild ("/");
Latch.await ();
}
}
Tree Node
This type can monitor the state of the node and monitor the state of the node's child nodes, similar to the combination of the two cache types above. This is also the concept of tree. It monitors the state of nodes in the entire tree. (As long as all leaf nodes under the listening path will listen)
Involves the following four classes.
Treecache
Treecachelistener
Treecacheevent
Childdata
Structural Treecache
And the key Treecache constructor is
Public Treecache (curatorframework client, String Path)
Add Monitor node status
When adding listener that monitor node state changes, we recommend using this method to manually pass in our constructed thread pool to ensure that the thread is controllable.
Treecache.getlistenable (). (T Listener, Executor Executor);
To use the cache, still call its Start method without having to call the Close method.
Getcurrentchildren () returns the status of the cache, the type is map. Getcurrentdata () returns data from the monitored path.
Finally, a complete code is also attached
Import Java.util.concurrent.CountDownLatch;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Org.apache.curator.framework.CuratorFramework;
Import Org.apache.curator.framework.CuratorFrameworkFactory;
Import Org.apache.curator.framework.recipes.cache.TreeCache;
Import Org.apache.curator.retry.ExponentialBackoffRetry;
/**
* ZK Link
*
* @author Jiangzhixiong
* @email xingxuan_jzx@foxmail.com
* @date October 12, 2015 5:18:21
*/
public class Treeclient {
IP and Port URLs
Private String URL;
Base path that requires listening
Private String BasePath;
private static Curatorframework client = NULL;
private static Treecache cache = NULL;
private static Zktreelistener listener = new Zktreelistener ();
private static Executorservice Executorservice = Executors.newsinglethreadexecutor ();
public void Init () throws Throwable {
if (BasePath = = null) {
BasePath = "O2o/zk/cache";
}
Modify the reconnect number, use the original thread for the reconnect listener, and do not re-create the thread exponentialbackoffretry (1000, 0)
Client = Curatorframeworkfactory.builder (). namespace (BasePath). ConnectString (URL). SESSIONTIMEOUTMS (5000). CONNECTIONTIMEOUTMS (3000). Retrypolicy (New Exponentialbackoffretry (1000,). Build ();
Client.start ();
/**
* Monitor the changes of child nodes
*/
Watchchild ("/product");
Watchchild ("/switch");
}
protected static void Watchchild (String path) throws Exception {
Use Treecachelistener to avoid the problem of circular listening child nodes
cache = new Treecache (client, path);
Cache.getlistenable (). AddListener (Listener, Executorservice);
Cache.start ();
}
Public String GetUrl () {
return URL;
}
public void SetUrl (String URL) {
This.url = URL;
}
Public String Getbasepath () {
return basepath;
}
public void Setbasepath (String basepath) {
This.basepath = BasePath;
}
public static void Main (string[] args) throws Throwable {
Countdownlatch latch = new Countdownlatch (1);
Client = Curatorframeworkfactory.builder (). Namespace ("O2o/zk/cache"). ConnectString ("192.168.200.98:2181"). SESSIONTIMEOUTMS (5000). CONNECTIONTIMEOUTMS (3000)
. Retrypolicy (New Exponentialbackoffretry (1000, 0)). Build ();
Client.start ();
/**
* Monitor the changes of child nodes
*/
Watchchild ("/product");
Watchchild ("/switch");
Latch.await ();
}
}
Import Java.util.Map;
Import Org.apache.commons.lang3.StringUtils;
Import Org.apache.curator.framework.CuratorFramework;
Import Org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
Import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
Import Org.apache.curator.framework.recipes.cache.TreeCacheListener;
Import Org.apache.logging.log4j.Level;
Import Org.apache.logging.log4j.LogManager;
Import Org.apache.logging.log4j.Logger;
Import Org.apache.logging.log4j.core.LoggerContext;
Import org.apache.logging.log4j.core.config.Configuration;
Import Org.apache.logging.log4j.core.config.LoggerConfig;
Import Com.jd.o2o.web.product.constants.zk.ZkSwitchEnum;
Import Com.jd.o2o.web.product.constants.zk.ZkValueEnum;
Import Com.jd.o2o.zk.cache.serializer.ZooKeeperSerializer;
Import Com.jd.o2o.zk.cache.serializer.impl.JdkSerializationZooKeeperSerializer;
/**
* Treecache ZK Listener
*
* @author Jiangzhixiong
* @email xingxuan_jzx@foxmail.com
* @date October 12, 2015 5:18:38
*/
public class Zktreelistener implements Treecachelistener {
Private final Logger Logger = Logmanager.getlogger (Treecachelistener. Class);
Private final zookeeperserializer<?> Defaultserializer = new Jdkserializationzookeeperserializer ();
@Override
public void Childevent (curatorframework client, treecacheevent event) throws Exception {
System.out.println (Event.getdata (). GetPath ());
Switch (Event.gettype ()) {
Case node_added:
if (Event.getdata (). GetData () = null) {
Break
}
Todo
Break
Case node_updated:
if (Event.getdata (). GetData () = null) {
Break
}
Todo
Break
Default
Break
}
}
}
https://my.oschina.net/jiangzhixiong/blog/537706