Zookeeper practices: Zookeeper cluster mode for Embedded running, zookeeper Cluster

Source: Internet
Author: User

Zookeeper practices: Zookeeper cluster mode for Embedded running, zookeeper Cluster
Many Zookeeper scenarios require that we embed Zookeeper as part of our distributed application system to provide distributed services. In this case, we need to start Zookeeper through a program. In this case, you can use the ZooKeeperServerMain class of the Zookeeper API to start the Zookeeper service.
 
The following is an example of starting the Zookeeper service in cluster mode.
 
Assume that the three machines running the Zookeeper cluster are fanbinx1, fanbinx2, and fanbinx3 respectively.
 

First, the configuration file zoo. cfg

tickTime=2000dataDir=/tmp/zookeeper/dataclientPort=2181initLimit=10syncLimit=5server.1=fanbinx1:2888:3888server.2=fanbinx2:2888:3888server.3=fanbinx3:2888:3888
The class that starts the Zookeeper cluster service, as follows:
* This class uses the same zoo. cfg configuration file to start the Zookeeper service.
* When starting the Zookeeper service on each machine, determine whether the current machine is defined in the zoo. cfg file. If the ID is obtained, generate a myid file and write the ID into it.
* Start the Zookeeper service.

package my.zookeeperstudy.server; import org.apache.commons.io.FileUtils;import org.apache.zookeeper.server.ServerConfig;import org.apache.zookeeper.server.ZooKeeperServerMain;import org.apache.zookeeper.server.quorum.QuorumPeerConfig; import java.io.File;import java.io.InputStream;import java.net.InetAddress;import java.util.Properties;import java.util.regex.Matcher;import java.util.regex.Pattern; public class ClusteredZKServer {     public static void main(String[] args) throws Exception {        InputStream is = ClusteredZKServer.class.getResourceAsStream("/my/zookeeperstudy/server/zoo.cfg");        Properties props = new Properties();        try {            props.load(is);        } finally {            is.close();        }         for (String key : props.stringPropertyNames()) {            Pattern pKey = Pattern.compile("^server\\.(\\d)");            Pattern pValue = Pattern.compile("([\\w|.]*):\\d*:\\d*");            Matcher mKey = pKey.matcher(key);            Matcher mValue = pValue.matcher(props.getProperty(key));            if (mKey.find() && mValue.find()) {                String id = mKey.group(1);                String host = mValue.group(1);                String thisHostName = InetAddress.getLocalHost().getHostName();                String thisHostAddress = InetAddress.getLocalHost().getHostAddress();                if (host.equals(thisHostName) || host.equals(thisHostAddress)) {                    //System.out.println(new File(props.getProperty("dataDir"), "myid").getAbsolutePath());                    FileUtils.write(new File(props.getProperty("dataDir"), "myid"), id);                    QuorumPeerConfig quorumConfig = new QuorumPeerConfig();                    quorumConfig.parseProperties(props);                     final ZooKeeperServerMain zkServer = new ZooKeeperServerMain();                    final ServerConfig config = new ServerConfig();                    config.readFrom(quorumConfig);                    zkServer.runFromConfig(config);                }            }        }    }}
The client test code is as follows. You can change the hostname to any machine in the cluster.
package my.zookeeperstudy.server; import org.apache.zookeeper.*; import java.util.List; public class Client {    public static void main(String[] args) throws Exception {        ZooKeeper zk = new ZooKeeper("fanbinx1:2181,fanbinx2:2181,fanbinx3:2181", 10000,                new Watcher() {                    public void process(WatchedEvent event) {                        System.out.println("event: " + event.getType());                    }                });         System.out.println(zk.getState());         zk.create("/myApps", "myAppsData".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);        zk.create("/myApps/App1", "App1Data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);        zk.create("/myApps/App2", "App2Data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);        zk.create("/myApps/App3", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);        zk.setData("/myApps/App3","App3Data".getBytes(), -1);         System.out.println(zk.exists("/myApps", true));        System.out.println(new String(zk.getData("/myApps", true, null)));         List<String> children = zk.getChildren("/myApps", true);        for (String child : children) {            System.out.println(new String(zk.getData("/myApps/" + child, true, null)));            zk.delete("/myApps/" + child,-1);        }         zk.delete("/myApps",-1);         zk.close();    }}

Test
* Run the ClusteredZKServer class on each machine in the cluster to start the Zookeeper service.
* Then, run the Client class on any machine to connect to Zookeeper and operate the data.


Link to the original article: Zookeeper practice-embedded running Zookeeper cluster mode

Related Article

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.