package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .*;
import ;
import ;
import ;
/**
* Created by IntelliJ IDEA.
* User: yingkuohao
* Date: 13-11-26
* Time: 上午10:54
* CopyRight:360buy
* Descrption:
* 分布式锁 :
* 1. 创建虚拟节点
* 2. 虚拟节点排序 ,获取最小的节点名称
* 3. 比较当前jvm创建的节点路径和最小的节点名称,如果想当则持有锁,否则等待或退出竞争。
* To change this template use File | Settings | File Templates.
*/
public class ZkLock {
private static final int SESSION_TIMEOUT = 10000;
static CountDownLatch countDownLatch = new CountDownLatch(1);
CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() {
public void run() {
("虚拟节点准备完毕,开始抢锁"); //后续线程执行
}
});
private static String parentLockPth = "/lockRoot";
volatile static boolean flag = false;
public static void main(String args[]) {
final Map<String, String> map = new HashMap<String, String>();
("node0", "192.168.192.68:2181");
("node1", "192.168.229.79:2181");
("node2", "192.168.229.80:2181");
final ZkLock zkLock = new ZkLock();
(("node0")); //创建lock父节点
checkParentIsOk(map); //校验父节点是否ok
//三个节点开始抢锁
for (int i = 0; i < 3; i++) {
final int finalI = i;
Thread thread = new Thread(new Runnable() {
public void run() {
try {
(); //三个节点同时执行
String key = "node" + finalI;
((key), finalI);
} catch (InterruptedException e) {
(); //To change body of catch statement use File | Settings | File Templates.
}
}
});
();
}
();//子线程一起开始
}
/**
* 换一个节点去校验是否父节点已经同步
*
* @param map
*/
private static void checkParentIsOk(Map<String, String> map) {
ZkApi zkApi = new ZkApi(("node1"));
ZooKeeper zooKeeper = ();
try {
String parentData = new String((parentLockPth, false, null));
(().getName() + "parentData=" + parentData);
} catch (KeeperException e) {
();
} catch (InterruptedException e) {
();
}
}
/**
* 创建锁的根节点:lockRoot
*
* @param serverPath
*/
public void creatRootNode(String serverPath) {
ZkApi zkApi = new ZkApi(serverPath);
ZooKeeper zooKeeper = ();
String parentLockPth = "/lockRoot";
(parentLockPth, "lockRootData", .OPEN_ACL_UNSAFE, ); //创建一个虚节点
try {
String parentData = new String((parentLockPth, false, null));
(().getName() + "parentData=" + parentData);
} catch (KeeperException e) {
();
} catch (InterruptedException e) {
();
}
}
/**
* 创建虚拟节点,然后抢锁,生成的结构如:
* /lockRoot/lock0
* /lockRoot/lock1
* /lockRoot/lock2
*
* @param serverPath
* @param i
*/
public void createEphemeralNode(String serverPath, int i) {
ZkApi zkApi = new ZkApi(serverPath);
String currentPath = "/lock" + i;
String wholePath = parentLockPth + currentPath; //节点路径 ,,形如/lockRoot/lock1
String testData = "lockdata"; // 节点初始化数据
List<ACL> aclList = .OPEN_ACL_UNSAFE; //节点的权限
// (path, testData, aclList, CreateMode.EPHEMERAL_SEQUENTIAL); //创建一个带顺序的虚节点成功后会带有一个序号,如lock1000000018, lock1000000019
(wholePath, testData, aclList, ); //创建一个虚节点
try {
(); //等待三个节点都创建成功后开始抢锁
} catch (InterruptedException e) {
();
} catch (BrokenBarrierException e) {
();
}
getLock((), parentLockPth, currentPath); //抢锁
}
/**
* 抢锁的核心逻辑
* 1. 创建虚拟节点
* 2. 虚拟节点排序 ,获取最小的节点名称
* 3. 比较当前jvm创建的节点路径和最小的节点名称,如果想当则持有锁,否则等待或退出竞争。
*
* @param zooKeeper
* @param parentLockPth
* @param currentPath
*/
private void getLock(ZooKeeper zooKeeper, String parentLockPth, String currentPath) {
try {
List<String> childNode = (parentLockPth, false); //获取孩子列表
(childNode); //把孩子列表排序 ,如:lock0,lock1,lock2
(().getName() + "孩子节点一共:" + ((), ","));
String firtNode = (0); //获取最小的节点,默认排序是升序,这里获取lock0
(().getName() + "firNode=" + firtNode + "cureentNode=" + currentPath);
firtNode = "/" + firtNode;
if ((firtNode)) {
//如果当前节点和第一个孩子节点的顺序相等,则可以获取锁
(().getName() + "[获取锁ok]" + ().getConfigStatus());
doAction();
(parentLockPth + firtNode, -1);//删除此节点,唤醒其他node
Stat stat = (parentLockPth + firtNode, false);
if (stat == null) {
(().getName() + "删除虚节点成功");
}
} else {
//如果当前节点的序号不是最小的,则等待获取锁
waitLock(zooKeeper, parentLockPth, currentPath);
}
} catch (KeeperException e) {
();
} catch (InterruptedException e) {
();
}
}
/**
* 等待锁,其实真正的来讲,分布式环境下获取不到锁的server就直接退出了,
* 就由获取锁的server去执行任务了。
* @param zooKeeper
* @param parentLockPth
* @param currentPath
*/
private void waitLock(ZooKeeper zooKeeper, String parentLockPth, String currentPath) {
try {
Stat stat = (parentLockPth + currentPath, false);
while (flag = false) {
(); //flag默认为false,该节点线程一直等待,直至拥有锁的线程修改flag状态,唤醒,
}
if (stat != null) {
//如果获取锁的节点还存在,说明上个节点还在用锁,当前节点只能等待。
(().getName() + "其他线程正在占用,请等待");
flag = false;
(2000);
}
(().getName() + "watiLock.重试,node[0]已不存在");
//如果获取锁的节点不存在了,说明上个节点获取的锁已经释放,它对应的虚节点已经被删除,这时可以继续尝试获取了
getLock(zooKeeper, parentLockPth, currentPath);
} catch (InterruptedException e) {
(); //To change body of catch statement use File | Settings | File Templates.
} catch (KeeperException e) {
(); //To change body of catch statement use File | Settings | File Templates.
}
}
private void getLock() {
doAction();
flag = true;
}
private void doAction() {
(().getName() + "获取锁成功,执行内容");
try {
().sleep(2000);
(().getName() + "睡眠完成");
} catch (InterruptedException e) {
(); //To change body of catch statement use File | Settings | File Templates.
}
}
}