Example of distributed lock for zookeeper in Linux

Source: Internet
Author: User
Tags zookeeper

First, prepare a zookeeper cluster environment, where you use a stand-alone simulation cluster environment and start the service in code mode.

Zookeeper Service

This assumes that starting three zookeeper services do cluster

Package my.zookeeperstudy;

Import Org.apache.commons.io.FileUtils;
Import Org.apache.zookeeper.server.quorum.QuorumPeerConfig;
Import Org.apache.zookeeper.server.quorum.QuorumPeerMain;

Import Java.io.File;
Import java.net.InetAddress;
Import java.util.Properties;

public class Zkserver {
protected String id = null;
protected String datadir = null;
protected String clientport = null;

Public zkserver (string ID, String datadir, String clientport) {
This.id = ID;
This.datadir = DataDir;
This.clientport = ClientPort;
}

public void StartServer () {
New Thread (New Runnable () {
@Override
public void Run () {
try {
Properties Props = new properties ();
Props.setproperty ("Ticktime", "2000");
Props.setproperty ("DataDir", DataDir);
Fileutils.write (New File (Props.getproperty ("DataDir"), "myID"), id);
Props.setproperty ("ClientPort", ClientPort);
Props.setproperty ("Initlimit", "10");
Props.setproperty ("Synclimit", "5");
String hostname = Inetaddress.getlocalhost (). GetHostName ();
Props.setproperty ("Server.1", hostname + ": 2,881:3,881");
Props.setproperty ("Server.2", hostname + ": 2,882:3,882");
Props.setproperty ("server.3", hostname + ": 2,883:3,883");

Quorumpeerconfig quorumconfig = new Quorumpeerconfig ();
Quorumconfig.parseproperties (props);

Quorumpeermain Quorumpeermain = new Quorumpeermain ();
Quorumpeermain.runfromconfig (Quorumconfig);
catch (Exception e) {
E.printstacktrace ();
}
}
). Start ();
}

}
Package my.zookeeperstudy;

public class ZKServer1 {

public static void Main (string[] args) throws Exception {
Zkserver zkserver = new Zkserver ("1", "/tmp/zookeeper1/data", "2181");
Zkserver.startserver ();
}

}
Package my.zookeeperstudy;

public class ZKServer2 {

public static void Main (string[] args) throws Exception {
Zkserver zkserver = new Zkserver ("2", "/tmp/zookeeper2/data", "2182");
Zkserver.startserver ();
}

}
Package my.zookeeperstudy;

public class ZKServer3 {

public static void Main (string[] args) throws Exception {
Zkserver zkserver = new Zkserver ("3", "/tmp/zookeeper3/data", "2183");
Zkserver.startserver ();
}

}
Distributed type Lock type Distributedlocker

Package my.zookeeperstudy.lock;

Import org.apache.zookeeper.*;

Import java.util.Collections;
Import java.util.List;

public class Distributedlocker {
Private Final zookeeper ZK;
Private final String Lockbasepath;
Private final String Lockname;
Private String Lockpath;

Public Distributedlocker (Zookeeper ZK, String Lockbasepath, String lockname) {
THIS.ZK = ZK;
This.lockbasepath = Lockbasepath;
This.lockname = Lockname;
}

public void Getlock () throws Keeperexception, Interruptedexception {
if (Zk.exists (Lockbasepath, true) = null) {
Zk.create (Lockbasepath, NULL, ZooDefs.Ids.OPEN_ACL_UNSAFE, createmode.persistent);
}
Lockpath = zk.create (Lockbasepath + "/" + Lockname, NULL, ZooDefs.Ids.OPEN_ACL_UNSAFE, createmode.ephemeral_sequential) ;
System.out.println ("Getlock path:" + Lockpath);
Final Object lock = new Object ();
Synchronized (lock) {
while (true) {
list<string> nodes = Zk.getchildren (Lockbasepath, New Watcher () {
@Override
public void process (Watchedevent event) {
Synchronized (lock) {
Lock.notifyall ();
}
}
});
Collections.sort (nodes);
SYSTEM.OUT.PRINTLN (nodes);
if (Lockpath.endswith (nodes.get (0))) {
Return
} else {
Lock.wait ();
}
}
}
}

public void ReleaseLock () throws Keeperexception, Interruptedexception {
Zk.delete (Lockpath,-1);
Lockpath = null;
}
}
Testing the Client class

There are still three clients in this simulation.

Package my.zookeeperstudy.lock;

Import org.apache.zookeeper.*;

public class Zkclient {
Private final String Lockbasepath = "/mylocks";
Private final String lockname = "Mylock";

public void start (String url) throws Exception {
Final Zookeeper ZK = new Zookeeper (URL, 10000, new Watcher () {
public void process (Watchedevent event) {
System.out.println ("event:" + Event.gettype ());
}
});

try {
Distributedlocker locker = new Distributedlocker (ZK, Lockbasepath, lockname);

System.out.println ("Before Get Lock");
Locker.getlock ();
System.out.println ("After get Lock");

System.out.println ("Do something");
Thread.Sleep (60 * 1000);

System.out.println ("Before release lock");
Locker.releaselock ();
System.out.println ("After release lock");
catch (Keeperexception e) {
E.printstacktrace ();
catch (Interruptedexception e) {
E.printstacktrace ();
}
}

}
Package my.zookeeperstudy.lock;

public class ZKClient1 {
public static void Main (string[] args) throws Exception {
Zkclient zkclient = new Zkclient ();
Zkclient.start ("localhost:2181");
}
}
Package my.zookeeperstudy.lock;

public class ZKClient2 {
public static void Main (string[] args) throws Exception {
Zkclient zkclient = new Zkclient ();
Zkclient.start ("localhost:2182");
}
}
Package my.zookeeperstudy.lock;

public class ZKClient3 {
public static void Main (string[] args) throws Exception {
Zkclient zkclient = new Zkclient ();
Zkclient.start ("localhost:2183");
}
}
Test

Start Zkserver1,zkserver2 and ZKServer3 first, the boot process will have errors, can be ignored, it is because the detection of other nodes when the connection failed, the production environment can be specific to ignore such errors.

Then start Zkclient1,zkclient2 and ZKClient3 in turn.

Observe three client log outputs, respectively.

Stop a client like ZKClient1 and then observe the log output.

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.