Zookeeper configuring synchronous Zookeeper programming

Source: Internet
Author: User

Distributed helper Zookeeper (iv)kissyoudyb 2013-12-05 17:41 read: 33 comments: 0Distributed helper Zookeeper (iii)kissyoudyb 2013-12-05 17:37 read: 48 comments: 0Distributed Assistant Zookeeper (ii)kissyoudyb 2013-12-05 17:25 read: 31 Comments: 0Distributed Assistant Zookeeper (i)kissyoudyb 2013-12-05 17:21 read: 46 Comments: 0 zookeeper is an important component in a distributed environment, because it can bring me a lot of convenience in distributed environment, greatly simplifies the complexity of distributed programming, this chapter will give a simulation example to demonstrate how to use Zookeeper API programming, To complete the configuration synchronization in a distributed environment. We all know that in a large-scale cluster, configuration files are usually essential, and many times I need to distribute the configuration files on the master to the individual slave to ensure the consistency of the overall configuration. When the cluster size is small, we may simply use remote copy or copy can be done, but when the cluster size is getting bigger, we find that this method is not only cumbersome, and error-prone, the most deadly is, if you change the configuration file a small part of things, you need to put all the configuration files, Overwrite the remote copy again, so how can you avoid this reaching thing?
in fact, using zookeeper, we can easily, highly reliable to help us do this, we just need to save the configuration file in the Zookeeper Znode, and then through watch to monitor the data changes, and then to help us achieve synchronization. A simple working diagram is as follows:

The summary process is as follows:
Serial number Realize 1 Start the ZK cluster 2 The client creates a znode in ZK and writes the data 3 Start watcher on each server, infinite hibernation 4 Client Update Znode Data 5 Watcher's Read method discovers data updates, drop-down to local, update local data
The code is as follows:
Package Com.sanjiesanxian;import Java.util.concurrent.countdownlatch;import Org.apache.zookeeper.CreateMode; Import Org.apache.zookeeper.watchedevent;import Org.apache.zookeeper.watcher;import Org.apache.zookeeper.zookeeper;import Org.apache.zookeeper.zoodefs.ids;import org.apache.zookeeper.data.Stat;/** * * Zookeeper implementation of distributed configuration synchronization * * @author Qindongliang * * ***/public class Syscconfig implements watcher{//zookeeper instance pri    Vate ZooKeeper ZK; Private Countdownlatch countdown=new Countdownlatch (1);//Sync tool private static final int timiout=5000;//timeout time private s    Tatic final String path= "/sanxian";                        Public Syscconfig (String hosts) {try{zk=new ZooKeeper (Hosts, Timiout, New Watcher () { @Override public void Process (Watchedevent event) {if (Event.getstate () . syncconnected==event.keeperstate.syncconnected) {//Prevent the zookeeper server from being connected before performing the related curd operation C Ountdown.countdown ();//EvenInitialization, completion, Empty counter}});    }catch (Exception e) {e.printstacktrace (); }}/*** * Write or UPDATE * data * @param path Write path * @param value written values * **/public void AddO      Rupdatedata (String path,string data) throws Exception {Stat stat=zk.exists (path, false); if (stat==null) {//is not created, and is written to zk.create (path, data.getbytes (), Ids.open_acl_unsafe, CREATEMODE.P      Ersistent);      System.out.println ("New, and write data successfully:");          }else{//exists, just update zk.setdata (path, data.getbytes (),-1);      SYSTEM.OUT.PRINTLN ("Update succeeded!");            }}/** * Read data * @param path read from * @return Read the contents of the data * * **/public String ReadData () throws exception{          String S=new string (Zk.getdata (PATH, this, null));    return s;                       }/** * Close zookeeper Connection * FREE RESOURCES * * **/public void Close () {try{ Zk.close ();        }catch (Exception e) {e.printstacktrace (); }} public static void Main (string[] args) throws Exception {syscconfig conf=new syscconfig ("10.2.143.5:           2181 "); Conf.addorupdatedata (PATH, "fix it, narrow escape.")      ");     Conf.addorupdatedata (PATH, "Under the Saints, are ants, even if the big ants, or ants."); Conf.addorupdatedata (PATH, "hard work, strength is kingly!")        ");    SYSTEM.OUT.PRINTLN ("Listener starts listening ...");    Conf.readdata ();    Thread.Sleep (Long.max_value);    Conf.readdata ();    Conf.close (); } @Override public void process (Watchedevent event) {try{if (Event.gettype () ==event.eventtype.nodedat        achanged) {System.out.println ("Change data:" +readdata ());         }}catch (Exception e) {e.printstacktrace (); }            }}

The analog client output is as follows:

    Client Listener Code syscconfig conf=new syscconfig ("10.2.143.5:2181");           Conf.addorupdatedata (PATH, "fix it, narrow escape.") ");      Conf.addorupdatedata (PATH, "Under the Saints, are ants, even if the big ants, or ants.");     Conf.addorupdatedata (PATH, "hard work, strength is kingly!") ");        SYSTEM.OUT.PRINTLN ("Listener starts listening ...");    Conf.readdata ();    Thread.Sleep (long.max_value);    Conf.readdata ();    Conf.close (); Update successful! Update successful!

The simulation server outputs are as follows:

public static void Main (string[] args) throws Exception {    //server-side Listener code    syscconfig conf=new syscconfig (" 10.2.143.36:2181 ");    Conf.addorupdatedata (PATH, "");    SYSTEM.OUT.PRINTLN ("Analog service listener starts listening ...");     Conf.readdata ();     Thread.Sleep (long.max_value);    Conf.close ();    } The analog service listener starts listening ... Data updated:  repair Real Day robbery, narrow escape. Data updated:  under the Saints, are ants, even if the big ants, or ants. Data updated:  


At this point, the service that uses zookeeper to complete the configuration synchronization is complete, and we can see that using zookeeper to write distributed programs is very simple and reliable.

Tags: Zookeeper

Zookeeper configuring synchronous Zookeeper programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.