教育行業(yè)A股IPO第一股(股票代碼 003032)

全國咨詢/投訴熱線:400-618-4000

Zookeeper客戶端動(dòng)態(tài)更新主節(jié)點(diǎn)狀態(tài)

更新時(shí)間:2018年07月27日09時(shí)41分 來源:傳智播客 瀏覽次數(shù):

某分布式系統(tǒng)中,主節(jié)點(diǎn)可以有多臺(tái),可以動(dòng)態(tài)上下線
任意一臺(tái)客戶端都能實(shí)時(shí)感知到主節(jié)點(diǎn)服務(wù)器的上下線


A、客戶端實(shí)現(xiàn)
public class AppClient {
        private String groupNode = "sgroup";
        private ZooKeeper zk;
        private Stat stat = new Stat();
        private volatile List<String> serverList;

        /**
         * 連接zookeeper
         */
        public void connectZookeeper() throws Exception {
                zk 
= new ZooKeeper("localhost:4180,localhost:4181,localhost:4182", 5000, new Watcher() {
                        public void process(WatchedEvent event) {
                                // 如果發(fā)生了"/sgroup"節(jié)點(diǎn)下的子節(jié)點(diǎn)變化事件, 更新server列表, 并重新注冊(cè)監(jiān)聽
                                if (event.getType() == EventType.NodeChildrenChanged 
                                        && ("/" + groupNode).equals(event.getPath())) {
                                        try {
                                                updateServerList();
                                        } catch (Exception e) {
                                                e.printStackTrace();
                                        }
                                }
                        }
                });

                updateServerList();
        }

        /**
         * 更新server列表
         */
        private void updateServerList() throws Exception {
                List<String> newServerList = new ArrayList<String>();

                // 獲取并監(jiān)聽groupNode的子節(jié)點(diǎn)變化
                // watch參數(shù)為true, 表示監(jiān)聽子節(jié)點(diǎn)變化事件. 
                // 每次都需要重新注冊(cè)監(jiān)聽, 因?yàn)橐淮巫?cè), 只能監(jiān)聽一次事件, 如果還想繼續(xù)保持監(jiān)聽, 必須重新注冊(cè)
                List<String> subList = zk.getChildren("/" + groupNode, true);
                for (String subNode : subList) {
                        // 獲取每個(gè)子節(jié)點(diǎn)下關(guān)聯(lián)的server地址
                        byte[] data = zk.getData("/" + groupNode + "/" + subNode, false, stat);
                        newServerList.add(new String(data, "utf-8"));
                }

                // 替換server列表
                serverList = newServerList;

                System.out.println("server list updated: " + serverList);
        }

        /**
         * client的工作邏輯寫在這個(gè)方法中
         * 此處不做任何處理, 只讓client sleep
         */
        public void handle() throws InterruptedException {
                Thread.sleep(Long.MAX_VALUE);
        }

        public static void main(String[] args) throws Exception {
                AppClient ac = new AppClient();
                ac.connectZookeeper();

                ac.handle();
        }
}



B、服務(wù)器端實(shí)現(xiàn)
public class AppServer {
        private String groupNode = "sgroup";
        private String subNode = "sub";

        /**
         * 連接zookeeper
         * @param address server的地址
         */
        public void connectZookeeper(String address) throws Exception {
                ZooKeeper zk = new ZooKeeper(
"localhost:4180,localhost:4181,localhost:4182", 
5000, new Watcher() {
                        public void process(WatchedEvent event) {
                                // 不做處理
                        }
                });
                // 在"/sgroup"下創(chuàng)建子節(jié)點(diǎn)
                // 子節(jié)點(diǎn)的類型設(shè)置為EPHEMERAL_SEQUENTIAL, 表明這是一個(gè)臨時(shí)節(jié)點(diǎn), 且在子節(jié)點(diǎn)的名稱后面加上一串?dāng)?shù)字后綴
                // 將server的地址數(shù)據(jù)關(guān)聯(lián)到新創(chuàng)建的子節(jié)點(diǎn)上
                String createdPath = zk.create("/" + groupNode + "/" + subNode, address.getBytes("utf-8"), 
                        Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
                System.out.println("create: " + createdPath);
        }
        
        /**
         * server的工作邏輯寫在這個(gè)方法中
         * 此處不做任何處理, 只讓server sleep
         */
        public void handle() throws InterruptedException {
                Thread.sleep(Long.MAX_VALUE);
        }
        
        public static void main(String[] args) throws Exception {
                // 在參數(shù)中指定server的地址
                if (args.length == 0) {
                        System.err.println("The first argument must be server address");
                        System.exit(1);
                }
                
                AppServer as = new AppServer();
                as.connectZookeeper(args[0]);
                as.handle();
        }
}



3.7.2分布式共享鎖的簡單實(shí)現(xiàn)
?        客戶端A
public class DistributedClient {
    // 超時(shí)時(shí)間
    private static final int SESSION_TIMEOUT = 5000;
    // zookeeper server列表
    private String hosts = "localhost:4180,localhost:4181,localhost:4182";
    private String groupNode = "locks";
    private String subNode = "sub";

    private ZooKeeper zk;
    // 當(dāng)前client創(chuàng)建的子節(jié)點(diǎn)
    private String thisPath;
    // 當(dāng)前client等待的子節(jié)點(diǎn)
    private String waitPath;

    private CountDownLatch latch = new CountDownLatch(1);

    /**
     * 連接zookeeper
     */
    public void connectZookeeper() throws Exception {
        zk = new ZooKeeper(hosts, SESSION_TIMEOUT, new Watcher() {
            public void process(WatchedEvent event) {
                try {
                    // 連接建立時(shí), 打開latch, 喚醒wait在該latch上的線程
                    if (event.getState() == KeeperState.SyncConnected) {
                        latch.countDown();
                    }

                    // 發(fā)生了waitPath的刪除事件
                    if (event.getType() == EventType.NodeDeleted && event.getPath().equals(waitPath)) {
                        doSomething();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        // 等待連接建立
        latch.await();

        // 創(chuàng)建子節(jié)點(diǎn)
        thisPath = zk.create("/" + groupNode + "/" + subNode, null, Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL_SEQUENTIAL);

        // wait一小會(huì), 讓結(jié)果更清晰一些
        Thread.sleep(10);

        // 注意, 沒有必要監(jiān)聽"/locks"的子節(jié)點(diǎn)的變化情況
        List<String> childrenNodes = zk.getChildren("/" + groupNode, false);

        // 列表中只有一個(gè)子節(jié)點(diǎn), 那肯定就是thisPath, 說明client獲得鎖
        if (childrenNodes.size() == 1) {
            doSomething();
        } else {
            String thisNode = thisPath.substring(("/" + groupNode + "/").length());
            // 排序
            Collections.sort(childrenNodes);
            int index = childrenNodes.indexOf(thisNode);
            if (index == -1) {
                // never happened
            } else if (index == 0) {
                // inddx == 0, 說明thisNode在列表中最小, 當(dāng)前client獲得鎖
                doSomething();
            } else {
                // 獲得排名比thisPath前1位的節(jié)點(diǎn)
                this.waitPath = "/" + groupNode + "/" + childrenNodes.get(index - 1);
                // 在waitPath上注冊(cè)監(jiān)聽器, 當(dāng)waitPath被刪除時(shí), zookeeper會(huì)回調(diào)監(jiān)聽器的process方法
                zk.getData(waitPath, true, new Stat());
            }
        }
    }

    private void doSomething() throws Exception {
        try {
            System.out.println("gain lock: " + thisPath);
            Thread.sleep(2000);
            // do something
        } finally {
            System.out.println("finished: " + thisPath);
            // 將thisPath刪除, 監(jiān)聽thisPath的client將獲得通知
            // 相當(dāng)于釋放鎖
            zk.delete(this.thisPath, -1);
        }
    }

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 10; i++) {
            new Thread() {
                public void run() {
                    try {
                        DistributedClient dl = new DistributedClient();
                        dl.connectZookeeper();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }

        Thread.sleep(Long.MAX_VALUE);
    }
}

?        分布式多進(jìn)程模式實(shí)現(xiàn):
public class DistributedClientMy {
        

        // 超時(shí)時(shí)間
        private static final int SESSION_TIMEOUT = 5000;
        // zookeeper server列表
        private String hosts = "spark01:2181,spark02:2181,spark03:2181";
        private String groupNode = "locks";
        private String subNode = "sub";
        private boolean haveLock = false;

        private ZooKeeper zk;
        // 當(dāng)前client創(chuàng)建的子節(jié)點(diǎn)
        private volatile String thisPath;

        /**
         * 連接zookeeper
         */
        public void connectZookeeper() throws Exception {
                zk = new ZooKeeper("spark01:2181", SESSION_TIMEOUT, new Watcher() {
                        public void process(WatchedEvent event) {
                                try {

                                        // 子節(jié)點(diǎn)發(fā)生變化
                                        if (event.getType() == EventType.NodeChildrenChanged && event.getPath().equals("/" + groupNode)) {
                                                // thisPath是否是列表中的最小節(jié)點(diǎn)
                                                List<String> childrenNodes = zk.getChildren("/" + groupNode, true);
                                                String thisNode = thisPath.substring(("/" + groupNode + "/").length());
                                                // 排序
                                                Collections.sort(childrenNodes);
                                                if (childrenNodes.indexOf(thisNode) == 0) {
                                                        doSomething();
                                                        thisPath = zk.create("/" + groupNode + "/" + subNode, null, Ids.OPEN_ACL_UNSAFE,
                                                                        CreateMode.EPHEMERAL_SEQUENTIAL);
                                                }
                                        }
                                } catch (Exception e) {
                                        e.printStackTrace();
                                }
                        }
                });

                // 創(chuàng)建子節(jié)點(diǎn)
                thisPath = zk.create("/" + groupNode + "/" + subNode, null, Ids.OPEN_ACL_UNSAFE,
                                CreateMode.EPHEMERAL_SEQUENTIAL);

                // wait一小會(huì), 讓結(jié)果更清晰一些
                Thread.sleep(new Random().nextInt(1000));

                // 監(jiān)聽子節(jié)點(diǎn)的變化
                List<String> childrenNodes = zk.getChildren("/" + groupNode, true);

                // 列表中只有一個(gè)子節(jié)點(diǎn), 那肯定就是thisPath, 說明client獲得鎖
                if (childrenNodes.size() == 1) {
                        doSomething();
                        thisPath = zk.create("/" + groupNode + "/" + subNode, null, Ids.OPEN_ACL_UNSAFE,
                                        CreateMode.EPHEMERAL_SEQUENTIAL);
                }
        }

        /**
         * 共享資源的訪問邏輯寫在這個(gè)方法中
         */
        private void doSomething() throws Exception {
                try {
                        System.out.println("gain lock: " + thisPath);
                        Thread.sleep(2000);
                        // do something
                } finally {
                        System.out.println("finished: " + thisPath);
                        // 將thisPath刪除, 監(jiān)聽thisPath的client將獲得通知
                        // 相當(dāng)于釋放鎖
                        zk.delete(this.thisPath, -1);
                }
        }

        public static void main(String[] args) throws Exception {
                DistributedClientMy dl = new DistributedClientMy();
                dl.connectZookeeper();
                Thread.sleep(Long.MAX_VALUE);
        }

        



作者:傳智播客javaEE
培訓(xùn)學(xué)院
首發(fā):http://java.itcast.cn/
0 分享到:
和我們?cè)诰€交談!