Zookeeper實現(xiàn)分布式鎖

之前寫過利用Redis實現(xiàn)分布式鎖的文章盐杂,剛好最近在學(xué)習ZooKpeer的一些知識踪少,想著利用Zookeeper去實現(xiàn)分布式鎖,查閱了一些文章卧斟,發(fā)現(xiàn)大家一致認為高并發(fā)場景下并不適合用ZooKeeper去實現(xiàn)殴边,性能存在問題。為什么呢珍语?ZooKeeper的性能問題锤岸,知乎上有人給出了兩條:

1. 本身不是為高可用性設(shè)計,master撐不住高流量容易導(dǎo)致系統(tǒng)crash板乙。
2. Paxos算法的復(fù)雜性是偷,選舉過程或許緩慢,結(jié)合上一點募逞,動輒需要重新選舉master導(dǎo)致耗時過長蛋铆。

有人將ZooKeeper類比于AQS(AbstractQueuedSynchronizer)AQS是完成多線程協(xié)同一致的利器放接,ZooKeeper是完成跨機器多進程之間的協(xié)同一致性的利器刺啦,也確實是有那么點相似之處(這里純屬瞎扯啊,但不得不說佩服別人的聯(lián)想能力)透乾。

image.png

image.png

Zookeeper實現(xiàn)分布式鎖的大致思路是:

1. 每個客戶端都去zookeeper上創(chuàng)建臨時的順序節(jié)點
2. 客戶端判斷當前自己創(chuàng)建的節(jié)點是不是最小的
3. 如果是的話洪燥,就獲得了執(zhí)行當前任務(wù)的鎖
4. 如果不是的話,就找到比自己小的節(jié)點乳乌,然后進行監(jiān)聽捧韵,如果被刪除的話,就可以獲得鎖

了解原理之后汉操,我們得去編碼實現(xiàn)分布式鎖:

package com.meituan.ZooKeeperDistributeLock;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.*;

/**
 * @Author: taomin
 * @Create_time: 2018-03-11
 * @Description: zookeeper實現(xiàn)分布式鎖
 */
public class LockTest {

    private String zkQurom = "127.0.0.1:2181";
    private String lockNameSpace = "/home";
    private final String nodeString = lockNameSpace + "/test";
    private ZooKeeper zk;

    public LockTest() {
        try {
            zk = new ZooKeeper(zkQurom, 6000, new Watcher() {
                public void process(WatchedEvent watchedEvent) {
                    System.out.println("Receive event " + watchedEvent);
                    if (Event.KeeperState.SyncConnected == watchedEvent.getState())
                        System.out.println("connection is established...");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void watchNode(final String nodeString, final Thread thread) throws InterruptedException {
        try {
            zk.exists(nodeString, new Watcher() {
                public void process(WatchedEvent watchedEvent) {
                    System.out.println("==" + watchedEvent.toString());
                    if (watchedEvent.getType() == Event.EventType.NodeDeleted) {
                        System.out.println(Thread.currentThread().getName() + " released Lock ==============");
                        thread.interrupt();
                    }
                    try {
                        zk.exists(nodeString, new Watcher() {
                            public void process(WatchedEvent watchedEvent) {
                                System.out.println("==" + watchedEvent.toString());
                                if (watchedEvent.getType() == Event.EventType.NodeDeleted) {
                                    System.out.printf(Thread.currentThread().getName() + " released Lock ==============");
                                    thread.interrupt();
                                }
                                try {
                                    zk.exists(nodeString, true);
                                } catch (KeeperException e) {
                                    e.printStackTrace();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (KeeperException e) {
            e.printStackTrace();
        }
    }

    private void ensureRootPath() throws InterruptedException {
        try {
            if (zk.exists(lockNameSpace, true) == null) {
                zk.create(lockNameSpace, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        }
    }

    public void unlock() {
        try {
            zk.delete(nodeString, -1);
            System.out.println(Thread.currentThread().getId() + " release Lock ==============");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
    }

    public boolean lock() throws InterruptedException {
        String path = null;
        ensureRootPath();
        watchNode(nodeString, Thread.currentThread());
        while (true) {
            try {
                path = zk.create(nodeString, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            } catch (KeeperException e) {
                System.out.println(Thread.currentThread().getName() + "  getting Lock but can not get ==============");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    System.out.println("thread is notify");
                }
            }
            if (path != null && !path.trim().equals("")) {
                System.out.println(Thread.currentThread().getName() + "  get Lock ==============");
                return true;
            }
        }
    }

    public static void main(String args[]) throws InterruptedException {
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(10);
        ThreadPoolExecutor service = new ThreadPoolExecutor(5, 10,
                60, TimeUnit.MICROSECONDS, queue);
        for (int i = 0; i < 4; i++) {
            service.execute(new Runnable() {
                public void run() {
                    LockTest test = new LockTest();
                    try {
                        test.lock();
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    test.unlock();
                }
            });
        }
        service.shutdown();
    }
}

輸出日志再来,從日志里面可以清楚看到線程競爭鎖的過程。

Receive event WatchedEvent state:SyncConnected type:None path:null
connection is established...
Receive event WatchedEvent state:SyncConnected type:None path:null
connection is established...
Receive event WatchedEvent state:SyncConnected type:None path:null
connection is established...
Receive event WatchedEvent state:SyncConnected type:None path:null
connection is established...
==WatchedEvent state:SyncConnected type:NodeCreated path:/home/test
==WatchedEvent state:SyncConnected type:NodeCreated path:/home/test
==WatchedEvent state:SyncConnected type:NodeCreated path:/home/test
==WatchedEvent state:SyncConnected type:NodeCreated path:/home/test
pool-1-thread-2  get Lock ==============

pool-1-thread-1  getting Lock but can not get ==============

pool-1-thread-4  getting Lock but can not get ==============

pool-1-thread-3  getting Lock but can not get ==============

==WatchedEvent state:SyncConnected type:NodeDeleted path:/home/test
==WatchedEvent state:SyncConnected type:NodeDeleted path:/home/test
pool-1-thread-3-EventThread released Lock ==============
==WatchedEvent state:SyncConnected type:NodeDeleted path:/home/test
pool-1-thread-2-EventThread released Lock ==============
==WatchedEvent state:SyncConnected type:NodeDeleted path:/home/test
thread is notify
pool-1-thread-2 release Lock ==============

pool-1-thread-4-EventThread released Lock ==============
pool-1-thread-1-EventThread released Lock ==============
thread is notify
thread is notify
Receive event WatchedEvent state:SyncConnected type:NodeCreated path:/home/test
connection is established...
Receive event WatchedEvent state:SyncConnected type:NodeCreated path:/home/test
connection is established...
pool-1-thread-3  get Lock ==============

pool-1-thread-4  getting Lock but can not get ==============

pool-1-thread-1  getting Lock but can not get ==============

Receive event WatchedEvent state:SyncConnected type:NodeDeleted path:/home/test
connection is established...
Receive event WatchedEvent state:SyncConnected type:NodeDeleted path:/home/test
connection is established...
pool-1-thread-3 release Lock ==============

pool-1-thread-4  get Lock ==============

pool-1-thread-1  getting Lock but can not get ==============

pool-1-thread-4 release Lock ==============

pool-1-thread-1  get Lock ==============

pool-1-thread-1 release Lock ==============

接觸Zookeeper不久磷瘤,理解不夠深刻芒篷,寫文章除了記錄自己的所見所聞外,同時也想借此來勉勵自己不放棄學(xué)習采缚,每天一點點進步针炉,明天會有不一樣的自己。
end~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末扳抽,一起剝皮案震驚了整個濱河市篡帕,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌贸呢,老刑警劉巖镰烧,帶你破解...
    沈念sama閱讀 206,723評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異楞陷,居然都是意外死亡怔鳖,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,485評論 2 382
  • 文/潘曉璐 我一進店門固蛾,熙熙樓的掌柜王于貴愁眉苦臉地迎上來结执,“玉大人,你說我怎么就攤上這事魏铅〔蹋” “怎么了?”我有些...
    開封第一講書人閱讀 152,998評論 0 344
  • 文/不壞的土叔 我叫張陵览芳,是天一觀的道長斜姥。 經(jīng)常有香客問我,道長沧竟,這世上最難降的妖魔是什么铸敏? 我笑而不...
    開封第一講書人閱讀 55,323評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮悟泵,結(jié)果婚禮上杈笔,老公的妹妹穿的比我還像新娘。我一直安慰自己糕非,他們只是感情好蒙具,可當我...
    茶點故事閱讀 64,355評論 5 374
  • 文/花漫 我一把揭開白布球榆。 她就那樣靜靜地躺著,像睡著了一般禁筏。 火紅的嫁衣襯著肌膚如雪持钉。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,079評論 1 285
  • 那天篱昔,我揣著相機與錄音每强,去河邊找鬼。 笑死州刽,一個胖子當著我的面吹牛空执,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播穗椅,決...
    沈念sama閱讀 38,389評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼辨绊,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了匹表?” 一聲冷哼從身側(cè)響起邢羔,我...
    開封第一講書人閱讀 37,019評論 0 259
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎桑孩,沒想到半個月后拜鹤,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,519評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡流椒,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,971評論 2 325
  • 正文 我和宋清朗相戀三年敏簿,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片宣虾。...
    茶點故事閱讀 38,100評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡惯裕,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出绣硝,到底是詐尸還是另有隱情蜻势,我是刑警寧澤,帶...
    沈念sama閱讀 33,738評論 4 324
  • 正文 年R本政府宣布鹉胖,位于F島的核電站握玛,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏甫菠。R本人自食惡果不足惜挠铲,卻給世界環(huán)境...
    茶點故事閱讀 39,293評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望寂诱。 院中可真熱鬧拂苹,春花似錦、人聲如沸痰洒。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,289評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至脯宿,卻和暖如春囱桨,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背嗅绰。 一陣腳步聲響...
    開封第一講書人閱讀 31,517評論 1 262
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留搀继,地道東北人窘面。 一個月前我還...
    沈念sama閱讀 45,547評論 2 354
  • 正文 我出身青樓,卻偏偏與公主長得像叽躯,于是被迫代替她去往敵國和親财边。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 42,834評論 2 345