linux中Zookeeper實戰之選舉

來源:互聯網
上載者:User

最近整理資料的時候發現了兩年前自己寫的一些Zookeeper的例子,今天整理了一下,放到這裡,也許以後用的著。

首先準備一個Zookeeper叢集環境,這裡使用單機類比叢集環境,並使用代碼方式啟動服務。

Zookeeper服務

這裡假定啟動三個Zookeeper服務做叢集

package my.zookeeperstudy;

import org.apache.commons.io.FileUtils;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.apache.zookeeper.server.quorum.QuorumPeerMain;

import java.io.File;
import java.net.InetAddress;
import java.util.Properties;

public class ZKServer {
    protected String id = null;
    protected String dataDir = null;
    protected String clientPort = null;

    public ZKServer(String id, String dataDir, String clientPort) {
        this.id = id;
        this.dataDir = dataDir;
        this.clientPort = clientPort;
    }

    public void startServer() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Properties props = new Properties();
                    props.setProperty("tickTime", "2000");
                    props.setProperty("dataDir", dataDir);
                    FileUtils.write(new File(props.getProperty("dataDir"), "myid"), id);
                    props.setProperty("clientPort", clientPort);
                    props.setProperty("initLimit", "10");
                    props.setProperty("syncLimit", "5");
                    String hostname = InetAddress.getLocalHost().getHostName();
                    props.setProperty("server.1", hostname + ":2881:3881");
                    props.setProperty("server.2", hostname + ":2882:3882");
                    props.setProperty("server.3", hostname + ":2883:3883");

                    QuorumPeerConfig quorumConfig = new QuorumPeerConfig();
                    quorumConfig.parseProperties(props);

                    QuorumPeerMain quorumPeerMain = new QuorumPeerMain();
                    quorumPeerMain.runFromConfig(quorumConfig);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
package my.zookeeperstudy;

public class ZKServer1 {

    public static void main(String[] args) throws Exception {
        ZKServer zkServer = new ZKServer("1", "/tmp/zookeeper1/data", "2181");
        zkServer.startServer();
    }

}
package my.zookeeperstudy;

public class ZKServer2 {

    public static void main(String[] args) throws Exception {
        ZKServer zkServer = new ZKServer("2", "/tmp/zookeeper2/data", "2182");
        zkServer.startServer();
    }

}
package my.zookeeperstudy;

public class ZKServer3 {

    public static void main(String[] args) throws Exception {
        ZKServer zkServer = new ZKServer("3", "/tmp/zookeeper3/data", "2183");
        zkServer.startServer();
    }

}
測試用戶端類

這裡有三個用戶端來類比選舉。

package my.zookeeperstudy.election;

import org.apache.zookeeper.*;

public class ZKClient {
    protected String id = null;
    protected String clientPort = null;
    protected String path = "/myapp_leader";

    public ZKClient(String id, String clientPort) {
        this.id = id;
        this.clientPort = clientPort;
    }

    protected void startClient() throws Exception {
        ZooKeeper zk = new ZooKeeper("localhost:" + clientPort, 10000,
                new Watcher() {
                    public void process(WatchedEvent event) {
                        System.out.println("event: " + event.getType());
                    }
                });

        while (true) {
            byte[] leader = null;
            try {
                leader = zk.getData(path, true, null);
            } catch(Exception e) {
                System.out.println("The leader is null.");
            }
            if (leader == null) {
                try {
                    zk.create(path, this.id.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
                } catch(Exception e) {
                    // ignore me
                }
            } else {
                System.out.println("The leader is: " + new String(leader));
            }
            Thread.sleep(1 * 1000);
        }
    }
}
package my.zookeeperstudy.election;

public class ZKClient1 {

    public static void main(String[] args) throws Exception {
        ZKClient zkClient = new ZKClient("1", "2181");
        zkClient.startClient();
    }

}
package my.zookeeperstudy.election;

public class ZKClient2 {

    public static void main(String[] args) throws Exception {
        ZKClient zkClient = new ZKClient("2", "2182");
        zkClient.startClient();
    }

}
package my.zookeeperstudy.election;

public class ZKClient3 {

    public static void main(String[] args) throws Exception {
        ZKClient zkClient = new ZKClient("3", "2183");
        zkClient.startClient();
    }

}
測試

首先依次啟動ZKServer1,ZKServer2和ZKServer3,啟動過程會有錯誤,可以忽略,那是因為檢測別的節點的時候串連失敗導致,生產環境可以針對具體情況忽略此類錯誤。

然後依次啟動ZKClient1,ZKClient2和ZKClient3。

分別觀察三個Client日誌輸出。

停止當前選舉到的leader,比如ZKClient1,然後觀察日誌輸出,一段時間後會重新選舉出一個leader。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.