Zookeeper provides a set of Java client APIs. This blog is mainly about creating sessions.
Create a project
First, create a simple Java project based on MAVEN management. Introduce zookeeper in the Pom file.
<dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.9</version></dependency>
Writing test Classes
For example, the simplest API is preferred.
publicZooKeeperint sessionTimeout, Watcher watcher)
Where connectstring represents the list of zookeeper server addresses to connect to, in the format: 192.168.0.1:2181. Multiple address stitching is supported, separated by commas. Where the address can also be spliced on the zookeeper operation path, such as: 192.168.0.1:2181/zk/test.
Sessiontimeout: Session timeout, unit "milliseconds". Monitor the effectiveness of the session through the heartbeat.
Watcher: Monitor the state change of the node, notify this watcher if changes occur, make corresponding processing. If you do not need to listen, you can set to null.
Test code:
PackageCom.secbro.learn;ImportOrg.apache.zookeeper.WatchedEvent;ImportOrg.apache.zookeeper.Watcher;ImportOrg.apache.zookeeper.ZooKeeper;ImportJava.io.IOException;ImportJava.util.Date;ImportJava.util.concurrent.CountDownLatch;/** * Created by Zhuzs on 2017/3/9. * * Public class testsession implements watcher{ Private StaticCountdownlatch Countdownlatch =NewCountdownlatch (1); Public Static void Main(string[] args)throwsIOException {Long StartTime =NewDate (). GetTime (); ZooKeeper ZooKeeper =NewZooKeeper ("192.168.0.1:2181", the,NewTestsession ());Try{countdownlatch.await (); }Catch(Interruptedexception e) {E.printstacktrace (); } System.out.println ("Create connection takes time:"+ (NewDate (). GetTime ()-startTime) +"MS"); System.out.println ("Connection Status:"+ zookeeper.getstate ()); } Public void Process(Watchedevent event) {System.out.println ("Receive Watcher event:"+ event);if(Event.KeeperState.SyncConnected = = Event.getstate ()) {Countdownlatch.countdown (); } }}
Because zookeeper client and server creation sessions are asynchronous procedures, use Countdownlatch to block threads, wait for server creation to complete, and send event notifications.
Printing results are:
Receivewatcherevent:WatchedEventstate:SyncConnectedtype:Nonepath:null创建连接花费时间:9155ms连接状态:CONNECTED
Other interfaces
publicZooKeeperint sessionTimeout, Watcher watcher, boolean canBeReadOnly)
This method has a canbereadonly parameter that indicates whether the current session supports read-only mode.
publicZooKeeperint sessionTimeout, Watcher watcher, longbyte[] sessionPasswd)
This method allows incoming SessionID and sessionpasswd to be reused for the session. The following methods are available:
zooKeeper.getSessionId();zooKeeper.getSessionPasswd()
The new connection is then created as a parameter. When SessionID and sessionpasswd are incorrect, the server returns the expired event.
Zookeeper Client API creation session (VI)