您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)zookeeper如何實(shí)現(xiàn)競(jìng)爭(zhēng)鎖的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
package com.hgs.sharelocks; import java.util.Collections; import java.util.List; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; public class ZKsharelocks { private ZooKeeper zk = null; private final static String connectString = "192.168.6.131:2181,192.168.6.132:2181,192.168.6.133:2181"; private final static int sessionTimeout = 2000; private final static String parentNode="/servers"; private final static String subNode="/sub"; private volatile String myPath = null; private boolean lockflag = false; public static void main(String[] args) throws Exception { ZKsharelocks sl = new ZKsharelocks(); sl.getConnect(); Thread.sleep(Long.MAX_VALUE); } public void getConnect() throws Exception{ //創(chuàng)建實(shí)例 zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() { @Override public void process(WatchedEvent event) { //判斷事件的類型以及路徑是否是業(yè)務(wù)路徑 if(event.getType()==EventType.NodeChildrenChanged&&event.getPath().equals(parentNode)) { List<String> inchild = null; try { //得到子節(jié)點(diǎn),繼續(xù)監(jiān)聽 inchild = zk.getChildren(parentNode, true); //排序 Collections.sort(inchild); //判斷返回的時(shí)間路徑不是null并且最小的子路經(jīng)是當(dāng)天路徑 if(myPath != null&&inchild.size()>0&&inchild.indexOf(myPath.substring(parentNode.length()+1))==0) { doSomthing(); Thread.sleep(2000); myPath=zk.create(parentNode+subNode, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); } } catch (Exception e) { e.printStackTrace(); } } } }); //首先創(chuàng)建一個(gè)臨時(shí)的序列的條目 myPath=zk.create(parentNode+subNode, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); //得到父節(jié)點(diǎn)下面的子目錄數(shù)并進(jìn)行監(jiān)聽 List<String> childs = zk.getChildren(parentNode, true); //判斷進(jìn)入到的時(shí)候是否只有自己,如果只有自己則可以做業(yè)務(wù)邏輯 if(childs.size()==1) { //業(yè)務(wù)方法,在業(yè)務(wù)方法內(nèi)有刪除myPath條目的操作 doSomthing(); //刪除完成后繼續(xù) myPath=zk.create(parentNode+subNode, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); } } public void doSomthing() throws Exception { System.out.println("get the lock..."+Thread.currentThread().getName()); //得到鎖完成業(yè)務(wù)后,刪除持有的鎖,即刪除該條目 zk.delete(myPath, -1); } }
感謝各位的閱讀!關(guān)于“zookeeper如何實(shí)現(xiàn)競(jìng)爭(zhēng)鎖”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。