ZK notes--Using Java Client access

Source: Internet
Author: User
Tags parent directory zookeeper

One: Introduction

ZK has run, and the next thing is how to use it to provide services,

I use MAVEN to create projects: rely on the following

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
   
	< dependency>
	  <groupId>org.slf4j</groupId>
	  <artifactid>slf4j-log4j12</artifactid >
	  <version>1.7.0</version>
	</dependency>

	<dependency>
	  < groupid>org.apache.zookeeper</groupid>
	  <artifactId>zookeeper</artifactId>
	  < Version>3.3.5</version>
	</dependency>

Note: The ZK version of the dependency is consistent with this version number and the version number of the startup Zkserver, and I am using a 3.3.5 version of Reliance to find a modest version.

Two: Demo code

Package COM.NETBOY.NETTY.ZK;
Import java.io.IOException;

Import java.util.List;
Import Org.apache.zookeeper.CreateMode;
Import org.apache.zookeeper.KeeperException;
Import org.apache.zookeeper.WatchedEvent;
Import Org.apache.zookeeper.Watcher;
Import Org.apache.zookeeper.ZooDefs.Ids;
Import Org.apache.zookeeper.ZooKeeper;
Import Org.slf4j.Logger;

Import Org.slf4j.LoggerFactory; /** * TODO:ZK Client demo, * to achieve the creation of nodes, parent-child node information, random access to child node information, delete node information function * Note: When using ZK dependencies, the version number needs to be the same as the ZK server version, or there will be different Often, that version is incompatible.
 This example uses the version 3.3.5. * * Netboy 2013-3-26 PM 12:57:35 * * Public class Zkdemo {private static final Logger Logger = Loggerfactory.getlog
	GER (Zkdemo.class);
	Private zookeeper ZK;
	Private String Parentdir = "/ServerName";
	Private String ChildDir1 = "/127.0.0.1:8081";
	Private String ChildDir2 = "/127.0.0.1:8082";

Private String childDir3 = "/127.0.0.1:8083"; /** * Initializes the ZK connection * * @throws IOException */public void init () throws IOException {ZK = new zookeeper ("127.0.0.1:8081,127.0.0.1:8082,127.0.0.1:8083 ", 1000, New Watcher () {//monitor all triggered events public void process (Watchedevent E Vent) {Logger.info ("the {} event has been triggered.")
				", Event.gettype ()); System.out.println ("The + event.gettype () +" event has been triggered.
			");
	}
		}); /** * Obtains the node information from ZK, the client randomly obtains the child node directory under the parent directory, has reached the random uniform obtains the host information * * * * * * * * * * */public void Getdirdata () throws Interruptedexception, Kee

		perexception {int count = 100;
		int b = 0;
		int c = 0;

		int d = 0;

		String Parentdir = "/ServerName";
		list<string> Childdir = Zk.getchildren (Parentdir, true);
			for (int i = 0; i < count; i++) {int temp = i% 3;
				Switch (temp) {case 0:b++;
			Break
				Case 1:c++;
			Break
				Case 2:d++;
			Break
			Default:break;
			} logger.info ("You get {}th child Node: {}", new Object[]{temp,childdir.get (temp)});
		Thread.Sleep (100);
		} logger.info ("The B = {}" the C ={} "the D ={}", New object[]{b,c,d}); StrinG string = new String (Zk.getdata (Parentdir, FALSE, null));
	Logger.info ("The search node is: {}", string);  /** * Creates a parent-child node, obtains the parent-child node content, and all child node directory names under the parent node * * @throws keeperexception * @throws interruptedexception/public void Createdata () throws Keeperexception, Interruptedexception {//Create parent-child node Zk.create (parentdir, "test". GetBytes (), Id

		S.open_acl_unsafe, createmode.persistent);
		Zk.create (Parentdir + childDir1, NULL, Ids.open_acl_unsafe, createmode.persistent);
		Zk.create (Parentdir + CHILDDIR2, NULL, Ids.open_acl_unsafe, createmode.persistent);

		Zk.create (Parentdir + childDir3, NULL, Ids.open_acl_unsafe, createmode.persistent);

		list<string> Childdir = Zk.getchildren (Parentdir, true);

		Logger.info ("The {} child dir: {}", new object[]{Parentdir,childdir});

		Byte[] Object = Zk.getdata (Parentdir, false, NULL);
			if (object!= null) {string string = new String (object); Logger.info ("You had created a node, it is: {} ={}",
					New object[]{parentdir,string});
		else {logger.info ("the dir: {} is null", Parentdir); /** * Deletes the created parent-child node * * @throws keeperexception * @throws interruptedexception/public void Delete () throws in Terruptedexception, Keeperexception {if (zk.exists (Parentdir + ChildDir1, false)!= null) {Zk.delete (Parentdir + CHI
		LdDir1,-1);
		} if (zk.exists (Parentdir + ChildDir2, false)!= null) {Zk.delete (Parentdir + childDir2,-1);
		} if (zk.exists (Parentdir + childDir3, false)!= null) {Zk.delete (Parentdir + childDir3,-1);
		} if (Zk.exists (Parentdir, false)!= null) {Zk.delete (Parentdir,-1);
	} logger.info ("You have deleted the node: {}", parentdir); public static void Main (string[] args) throws IOException, Keeperexception, INTERRUPTEDEXCEP
		tion {//Create a connection to the server Zkdemo demo = new Zkdemo ();
        Demo.init ();
		
		If the node you created already exists, delete demo.delete () first;
		
		Demo.createdata (); Obtain the information Demo.getdirda of the subdirectory node evenlyTa ();
	Deletes the new node created Demo.delete (); }
}


The comments in the code are more clear, not here.


Three: Run

The following log will appear when the operation succeeds:




The Demo.delete () in the main function is commented out. Run again.

Use ZK's self-brought client view:



SOURCE Download Link: Zkclientdemo source code

*************************************************************************************************************** **********************
Do it,insist It,enjoy it


*************************************************************************************************************** **********************





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.