Synchronize the cluster configuration with ZooKeeper, when you need to modify all the node configuration, update the configuration to a node of ZooKeeper, causing the node data to change,
Local watcher on all other nodes that need to be configured synchronously immediately discovers the change in node state and updates the latest data to a local
Change the official demo, in response to watcher with Conffileutil update the local configuration can be
[Java]View Plaincopyprint?
- Public class Executor implements Watcher, Runnable,
- Datamonitor.datamonitorlistener {
- String Znode;
- DataMonitor DM;
- ZooKeeper ZK;
- String filename;
- Public Executor (string hostport, String znode, string filename)
- throws Keeperexception, IOException {
- this.filename = filename;
- ZK = New ZooKeeper (Hostport, N, this );
- DM = New DataMonitor (ZK, Znode, this );
- }
- public static void Main (string[] args) {
- args = new string[3];
- args[0] = Constant.zkpeer;
- args[1] = Constant.znode;
- args[2] = "";
- String hostport = args[0];
- String Znode = args[1];
- String filename = args[2];
- try {
- New Executor (Hostport, Znode, filename). Run ();
- } catch (Exception e) {
- E.printstacktrace ();
- }
- }
- public void Process (Watchedevent event) {
- Dm.process (event);
- }
- public Void Run () {
- try {
- synchronized (this) {
- While (!dm.dead) {
- Wait ();
- }
- }
- } catch (Interruptedexception e) {
- }
- }
- public void closing (int rc) {
- synchronized (this) {
- Notifyall ();
- }
- }
- /**
- * Processing Data
- */
- public void exists (byte[] data) {
- System.out.println ("... Invoked:Executor.exists (byte[] data) ... ");
- Conffileutil.sync (data);
- }
- }
The Executor above is used to establish and maintain connections with Znode.
DataMonitor is still responsible for receiving event processing results, and this class is basically not changed.
DataMonitor delegate Executor to update local configuration when watcher is triggered
Full code See GITHUB
One thing to be aware of when updating nodes
[Java]View Plaincopyprint?
- Zk.setdata (Constant.znode, Bytes,-1, null, null);
This byte[] is limited in size, and if it exceeds the limit, ZooKeeper will not tell you that the official document is 1M, which I did not test.
When the update data is unsuccessful and there are no exceptions, you need to check if the array is too long.
Synchronizing a cluster configuration with ZooKeeper