基於ZooKeeper的一種簡單分布式鎖的實現

來源:互聯網
上載者:User

        ZooKeeper是一個分布式的,開放源碼的分布式應用程式協調服務。基於ZooKeeper,我們可以實現一種簡單的分布式互斥鎖,包括可重新進入與不可重新進入。代碼如下:

import java.io.IOException;import java.util.ArrayList;import java.util.Random;import org.apache.zookeeper.CreateMode;import org.apache.zookeeper.KeeperException;import org.apache.zookeeper.WatchedEvent;import org.apache.zookeeper.Watcher;import org.apache.zookeeper.ZooDefs.Ids;import org.apache.zookeeper.ZooKeeper;public class TestZooKeeperDistributeLock {// 是否為可重新進入鎖private boolean reentrant = false;public boolean isReentrant() {return reentrant;}private ZooKeeper zk = null;public ZooKeeper getZk() {return zk;}public TestZooKeeperDistributeLock(boolean reentrant) {this.reentrant = reentrant;// 初始化環境:串連Zookeeper並建立根目錄init();}private void init() {try {System.out.println("...");System.out.println("...");System.out.println("...");System.out.println("...");System.out.println("開始串連ZooKeeper...");// 建立與ZooKeeper伺服器的串連zkString address = "192.168.1.226:2181";int sessionTimeout = 3000;zk = new ZooKeeper(address, sessionTimeout, new Watcher() {// 監控所有被觸發的事件public void process(WatchedEvent event) {if (event.getType() == null || "".equals(event.getType())) {return;}System.out.println("已經觸發了" + event.getType() + "事件。");}});System.out.println("ZooKeeper串連建立成功。");Thread.currentThread().sleep(1000l);System.out.println("...");System.out.println("...");System.out.println("...");System.out.println("...");// 建立根目錄節點// 路徑為/tmp_root_path// 節點內容為字串"我是根目錄/tmp_root_path"// 建立模式為CreateMode.PERSISTENTSystem.out.println("開始建立根目錄節點/tmp_root_path...");zk.create("/tmp_root_path", "我是根目錄/tmp_root_path".getBytes(),Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);System.out.println("根目錄節點/tmp_root_path建立成功。");Thread.currentThread().sleep(1000l);System.out.println("...");System.out.println("...");System.out.println("...");System.out.println("...");} catch (Exception e) {zk = null;}}public void destroy() {// 刪除根目錄節點try {System.out.println("開始刪除根目錄節點/tmp_root_path...");zk.delete("/tmp_root_path", -1);System.out.println("根目錄節點/tmp_root_path刪除成功。");} catch (InterruptedException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (KeeperException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}// 關閉串連if (zk != null) {try {zk.close();System.out.println("釋放ZooKeeper串連成功。");} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public static void main(String[] args) {final TestZooKeeperDistributeLock testZooKeeperDistributeLock = new TestZooKeeperDistributeLock(true);final Random radom = new Random();try {Thread.currentThread().sleep(1000l);} catch (InterruptedException e2) {// TODO Auto-generated catch blocke2.printStackTrace();}ArrayList<Thread> threadList = new ArrayList<Thread>();for (int i = 0; i < 4; i++) {Thread thread = new Thread() {@Overridepublic void run() {boolean locked = false;while (true) {try {// 建立需要擷取鎖的目錄節點,建立成功則說明能夠擷取到鎖,建立不成功,則說明鎖已被其他線程(哪怕是不同進程的)擷取// 路徑為/tmp_root_path/lock// 節點內容為當前線程名// 建立模式為CreateMode.PERSISTENTSystem.out.println("線程"+ Thread.currentThread().getName()+ "嘗試擷取鎖...");testZooKeeperDistributeLock.getZk().create("/tmp_root_path/lock",Thread.currentThread().getName().getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);System.out.println("線程"+ Thread.currentThread().getName()+ "成功擷取到鎖。");locked = true;System.out.println("線程"+ Thread.currentThread().getName()+ "開始處理商務邏輯...");Thread.currentThread().sleep(3000 + radom.nextInt(3000));System.out.println("線程"+ Thread.currentThread().getName()+ "商務邏輯處理完畢。");} catch (Exception e) {if (testZooKeeperDistributeLock.isReentrant()) {try {String lockThread = new String(testZooKeeperDistributeLock.getZk().getData("/tmp_root_path/lock",false, null));if (lockThread != null) {// 當前線程與擷取到的鎖線程名一致,重入鎖if (lockThread.equals(Thread.currentThread().getName())) {System.out.println("線程"+ Thread.currentThread().getName()+ "成功重入鎖。");locked = true;System.out.println("線程"+ Thread.currentThread().getName()+ "開始處理商務邏輯...");Thread.currentThread().sleep(3000 + radom.nextInt(3000));System.out.println("線程"+ Thread.currentThread().getName()+ "商務邏輯處理完畢。");} else {System.out.println("線程"+ Thread.currentThread().getName()+ "嘗試擷取鎖失敗,鎖被線程"+ lockThread + "佔用。");}}} catch (KeeperException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (InterruptedException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}} else {System.out.println("線程"+ Thread.currentThread().getName()+ "嘗試擷取鎖失敗。");}try {Thread.currentThread().sleep(3000 + radom.nextInt(3000));} catch (InterruptedException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}} finally {try {if (locked) {System.out.println("線程"+ Thread.currentThread().getName()+ "開始釋放鎖...");testZooKeeperDistributeLock.getZk().delete("/tmp_root_path/lock", -1);System.out.println("線程"+ Thread.currentThread().getName()+ "成功釋放鎖。");Thread.currentThread().sleep(3000 + radom.nextInt(3000));}} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (KeeperException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {locked = false;}}}}};threadList.add(thread);thread.start();}try {Thread.currentThread().sleep(1000 * 20);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}for(int i = 0; i < threadList.size(); i++){Thread thread = threadList.get(i);thread.stop();}// 釋放資源testZooKeeperDistributeLock.destroy();}}
        運行結果如下:

............開始串連ZooKeeper...ZooKeeper串連建立成功。已經觸發了None事件。............開始建立根目錄節點/tmp_root_path...根目錄節點/tmp_root_path建立成功。............線程Thread-0嘗試擷取鎖...線程Thread-2嘗試擷取鎖...線程Thread-3嘗試擷取鎖...線程Thread-1嘗試擷取鎖...線程Thread-0成功擷取到鎖。線程Thread-0開始處理商務邏輯...線程Thread-1嘗試擷取鎖失敗,鎖被線程Thread-0佔用。線程Thread-2嘗試擷取鎖失敗,鎖被線程Thread-0佔用。線程Thread-3嘗試擷取鎖失敗,鎖被線程Thread-0佔用。線程Thread-1嘗試擷取鎖...線程Thread-1嘗試擷取鎖失敗,鎖被線程Thread-0佔用。線程Thread-2嘗試擷取鎖...線程Thread-2嘗試擷取鎖失敗,鎖被線程Thread-0佔用。線程Thread-3嘗試擷取鎖...線程Thread-3嘗試擷取鎖失敗,鎖被線程Thread-0佔用。線程Thread-0商務邏輯處理完畢。線程Thread-0開始釋放鎖...線程Thread-0成功釋放鎖。線程Thread-2嘗試擷取鎖...線程Thread-2成功擷取到鎖。線程Thread-2開始處理商務邏輯...線程Thread-1嘗試擷取鎖...線程Thread-1嘗試擷取鎖失敗,鎖被線程Thread-2佔用。線程Thread-3嘗試擷取鎖...線程Thread-3嘗試擷取鎖失敗,鎖被線程Thread-2佔用。線程Thread-0嘗試擷取鎖...線程Thread-0嘗試擷取鎖失敗,鎖被線程Thread-2佔用。線程Thread-2商務邏輯處理完畢。線程Thread-2開始釋放鎖...線程Thread-2成功釋放鎖。線程Thread-3嘗試擷取鎖...線程Thread-1嘗試擷取鎖...線程Thread-3成功擷取到鎖。線程Thread-3開始處理商務邏輯...線程Thread-1嘗試擷取鎖失敗,鎖被線程Thread-3佔用。線程Thread-0嘗試擷取鎖...線程Thread-0嘗試擷取鎖失敗,鎖被線程Thread-3佔用。線程Thread-2嘗試擷取鎖...線程Thread-2嘗試擷取鎖失敗,鎖被線程Thread-3佔用。線程Thread-3商務邏輯處理完畢。線程Thread-3開始釋放鎖...線程Thread-3成功釋放鎖。線程Thread-0嘗試擷取鎖...線程Thread-0成功擷取到鎖。線程Thread-0開始處理商務邏輯...線程Thread-1嘗試擷取鎖...線程Thread-1嘗試擷取鎖失敗,鎖被線程Thread-0佔用。線程Thread-2嘗試擷取鎖...線程Thread-2嘗試擷取鎖失敗,鎖被線程Thread-0佔用。線程Thread-0開始釋放鎖...開始刪除根目錄節點/tmp_root_path...線程Thread-0成功釋放鎖。根目錄節點/tmp_root_path刪除成功。釋放ZooKeeper串連成功。
        樣本可能略顯粗糙,但是大體原理就是這樣。我們可以利用ZooKeeper上一個固定位置的節點有無,來判斷鎖是否被擷取到。當某一線程來臨時,如果節點不存在,則說明沒有其他線程佔用對應鎖,調用ZooKeeper的create()方法建立節點,標識分布式鎖已被當前線程佔用。待業務處理完畢後,再調用ZooKeeper的delete()方法刪除節點,則完成鎖的釋放。

        同時,我們可以對應節點寫入線程名等區分線程唯一性的欄位來標識鎖被哪個線程佔用。而當再有線程要擷取鎖時,如果為不可重新進入鎖,無論哪個線程,即便是持有鎖的線程本身,也得等鎖釋放後再擷取鎖,如果為可重新進入鎖,則判斷當前線程唯一性欄位與對應節點中的資料是否一致即可。

        當然,也可以利用ZooKeeper的CreateMode中PERSISTENT_SEQUENTIAL,一種順序自動編號的目錄節點,檢測某節點的子目錄,來實現可以排隊的優先順序鎖。這個留待以後我們再研究。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.