Start making? Zookeeper's API

Source: Internet
Author: User
Tags zookeeper client

in the previous chapters, we introduced the basic operation of zookeeper using the Zkcli tool. starting with this chapter, we'll see how the API is used in the app. Let's start by introducing How to use the Zookeeper API for development, showing how to create a session and implement a monitoring point (Watcher). We're still coding from the master-pattern example .

1.1 establishing a zookeeper session

The Zookeeper API is built around the zookeeper handle (handle), with each API tuned it is necessary to pass this handle. This handle represents a conversation with the zookeeper. In Figure 3-1, if a session that has been established with the zookeeper server is disconnected, the session is migrated to another zookeeper server. As long as the session is alive, the handle is still valid, and the Zookeeper client library will continue to maintain this active connection to ensure that the session is alive with the zookeeper service. If the handle is closed, the Zookeeper client library tells the zookeeper server to terminate the session. If zookeeper discovers that the client is dead, it will invalidate the session. If the client attempts to reconnect to the zookeeper server after the connection is made using the handle corresponding to the previously invalid session, the Zookeeper server notifies the guest -side library that the session has been invalidated. Any operation that uses this handle will return an error.

The constructor for creating the zookeeper handle is as follows:

ZooKeeper (String connectstring,int  Sessiontimeout,watcher watcher)

which

ConnectString
Contains the host name and port of the zookeeper server. We previously connected via ZKCLI
These servers are already listed in the Zookeeper service.

Sessiontimeout
The maximum time, in milliseconds, that zookeeper waits for the client to communicate, and then the sound
The Ming session has died. Currently we use 15000, or 15 seconds. This means that if zookeeper and
The client has 15 seconds to communicate, and zookeeper terminates the client's session. Need
Note that this value is relatively large, but it can be very useful for our subsequent experiments. Zookeeper will
The general setting time-out is 5-10 seconds.
Watcher
an object that is used to receive session events, which requires our own creation. Because
Wacher is defined as an interface, so we need to implement one ourselves, and then initialize the class's
instance and passes the zookeeper in the constructor. The client uses the Watcher interface to monitor and
the health of the session between zookeeper. Establish or lose connectivity with the zookeeper server
event occurs. They can also be used to monitor changes in zookeeper data. In the end, such as
The zookeeper session expires, and the event is passed through the Watcher interface to notify the client
the application.

1.1.1 Implements a watcher

in order to receive notifications from zookeeper, we need to implement a monitoring point. Let's start with A closer look at the Watcher interface, which is defined as follows:

 Public Interface Watcher {void  process (Watchedevent event);}

This interface does not have much content, we have to implement it ourselves, but now we are simply
To output events. So let's start with an example from a class called Master:

ImportOrg.apache.zookeeper.ZooKeeper;ImportOrg.apache.zookeeper.Watcher; Public classMasterImplementsWatcher {ZooKeeper ZK; String Hostport; Master (String hostport) { This. Hostport =Hostport;①}voidStartzk () {ZK=NewZooKeeper (Hostport, 15000, This); ②} Public voidprocess (Watchedevent e) {System.out.println (e); ③} Public Static voidMain (String args[])throwsException {Master m=NewMaster (args[0]); M.startzk ();//wait for a bitThread.Sleep (60000); ④}}

④ after we connect to zookeeper, there is a thread in the background to maintain this
Zookeeper session. The thread is a daemon thread, that is, even if the thread is active,
Programs can also exit. So we hibernate for a while before the program exits so that we can see
To the occurrence of the event.

A daemon is a thread that provides a generic service in the background while the program is running, such as a garbage collection thread that is a competent guardian, and that thread is not an integral part of the program. Therefore, when all non-daemon threads end, the program terminates and kills all the daemon threads in the process. Conversely, the program will not terminate as long as any non-daemon threads are still running.

There is no essential difference between a daemon thread and a user thread: The only difference is the departure of the virtual machine: If the user thread is all out of operation, only the daemon thread is present, and the virtual machine exits. Because there is no guardian, the daemon will have no work to do, there is no need to continue to run the program.

Run:

...-INFO [...]-Client environment:zookeeper.version=3.4.5-1392090, ... ① ...-INFO [...]-Initiating client connection,connectstring=127.0.0.1:2181 ... ② ...-INFO [...]-Opening socket connection to serverlocalhost/127.0.0.1:2181. ...-info [...]-Socket connection established to localhost/127.0.0.1:2181,initiating session ...-info [...]-Sessi On establishment complete on serverlocalhost/127.0.0.1:2181, ... ③watchedevent state:syncconnected Type:none Path:null④

The Zookeeper Client API generates a lot of log messages that enable users to understand what has happened you. The logs are very detailed and can be disabled by the configuration file, but these messages are very useful at the time of the launch, and even after the formal deployment, there are some things that we do not want to send , and These log messages are also valuable.

① front?? The log message describes the implementation and environment of the zookeeper client. ② When a client initializes a connection to a zookeeper server, is it the initial connection or subsequent reconnection that will be produced? These log messages. ③ This message shows information about the connection after the connection was established, including the host and end of the client connection, and the time-out that the session negotiated with the server. If the server discovers that the requested session time-out is too short or too long, the server adjusts the session time-out. ④ The last one? is not the output of the Zookeeper library, which is the Watchevent object that we implement in the Watcher.process (watchedevent e) function.
1.1.2 Example of running watcher

If we start the master node without starting the zookeeper service, what happens? I > We can try. Stop the service, then run master and see what? In the previous output, < Span style= "FONT-SIZE:18PX;" > We can't connect to the zookeeper server, so we can't see this information.

  Now we start the server and then run master, then stop the server and keep Master continues to run. You'll see disconnected things happen after the syncconnected event .

  when developers see the disconnected event, some people think they need to create a newzookeeper handle to reconnect the service. Don't do this! When you start the server and then startMaster, and then restart the server to see what happened. You see the syncconnected incidentafter the disconnected event, and then another syncconnected event. Zookeeper CustomerThe end Library is responsible for reconnecting the service for you. When a network outage or server failure is unfortunate,Zookeeper can handle these failure problems.

 we need to know that zookeeper itself may also have these failure problems. AThe zookeeper server may fail or lose network connectivity, like when we stop the main nodethe proposed scenario. If the Zookeeper service consists of at least three servers, then a server'sfailure does not cause a service outage. The client will also receive the disconnected event soon afteris the syncconnected event.

Note: Zookeeper Management connection

Please do not try to manage the Zookeeper client connection yourself. The Zookeeper client library will
The connection between the monitoring and the service, the client library not only tells us the connection problem, but also actively
Try to reestablish communication. The General Client development Library will quickly rebuild the session to minimize the application
The impact. Therefore, do not close the session and then start a new session, which will increase the system negative
and lead to a longer period of interruption.

  

the client is like nothing but sleep, and we pass events that cansee what's going on backstage. We can also look at what's happening on the zookeeper server.you. Zookeeper has two types of management interfaces: JMX and four-letter commands. The 10th chapter will go deepTo discuss these interfaces, now let's look at the server using the two four-letter commands stat and dumpwhat happened on it. to use these commands, you need to first connect to client port 2181 via Telnet, and then enterThese commands (enter the ENTER key after the command). For example, if you start the master program,using the Stat command, we will see the following output information:

$ telnet 127.0.0.1 2181Trying 127.0.0.1...Connected to 127.0.0.1.Escape character is ' ^] '. Statzookeeper version:3.4.5-13 92090, built on 09/30/2012 17:52 gmtclients:/127.0.0.1:39470[1] (queued=0,recved=3,sent=3)/127.0.0.1:39471[0] (queued =0,recved=1,sent=0) Latency Min/avg/max:0/5/48received:34sent:33connections:2outstanding:0zxid:0x17mode: Standalonenode Count:4connection closed by foreign host.

we see from the output information that there are two clients connected to the zookeeper server. One is the Master program and the other is Telnet connection. If we start the Master program and make the dump command, we will see the following output messages :

$ telnet 127.0.0.1 2181Trying 127.0.0.1...Connected to 127.0.0.1.Escape character is ' ^] '. Dumpsessiontracker Dump: Session Sets (3): 0 expire at Wed-20:34:00 PST 2012:0 expire at Wed-20:34:02 PST 2012:1 expire at Wed 28 20:34:04 PST 2012:0x13b4a4d22070006ephemeral nodes dump:sessions with ephemerals (0): Connection closed by foreign host.

we see an active session from the output message, this session belongs to the master thread .order. We can also see how long this session will expire. The expiration time of the session timeout is takenThe value specified when we created the Zookeeper object. Let me end the master program and use the dump command again to see the session information for the activity. you will notice that the conversation disappears after a period of time. This is because the session time-out is too late to, the server will not end this session. Of course, the client will continue to continue with the zookeeper servicethe expiration time of the active connection of the device. when Master finishes, the best way is to make the session disappear immediately. This can be done byZookeeper.close () method to end. Once the Close method is called, the Zookeeper object is actuallythe session represented by the example will be destroyed. Let's add a close call to the sample program:

void Stopzk () throws Exception {Zk.close ();} public static void Main (String args[]) throws Exception {Master m = new Master (args[0]); M.startzk ();//wait for a Bitthrea D.sleep (60000); M.stopzk ();}

Now we can run the Master program again and run the dump command to see if the session
Still alive. Because the session is closed in the master program, zookeeper closes the session before
There is no need to wait for the session to time out.

Start making? Zookeeper's API

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.