一、windows10環境搭建zookeeper集羣
今天嘗試在自己的windows系統中搭建zokeeper集羣環境,記錄下步驟和出現的問題以及解決方法。
搭建環境
1)電腦裏下載的zookeeper版本是3.4.5,解壓到D盤,創建3個目錄,分別爲server1,servr2,server3,將解壓好的文件分別複製一份到這三個目錄中。
2)配置。進入到conf目錄中,將zoo_sample.cfg重命名爲zoo.cfg,並且修改cfg文件的屬性
# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just
# example sakes.
dataDir=D:/DataBase/zookeeper/server1/zookeeper-3.4.5/data
# the port at which the clients will connect
clientPort=2181
server.1=localhost:2887:3887
server.2=localhost:2888:3888
server.3=localhost:2889:3889
其中,dataDir可以自己選擇目錄,是存放myid文件的地方,data文件夾需要自己創建,其他的兩個文件夾的配置也要修改,server2文件夾裏面的clientPort就可以寫成2182,dataDir也需要相對應修改,依次類推。
3)進入server1文件夾裏面的zookeeper文件夾裏,創建data文件夾,並且創建myid文件。
注意,這塊需要保證文件的編碼格式,我是直接在目錄裏使用鼠標直接右鍵生成文件,最後報錯了。想到直接在cmd進入到data文件夾裏,使用echo命令創建,這樣就可以創建好了,最後還得看看是否myid文件裏只有這個一個數字(空格,換行之類的都不行),其他兩個文件夾也一樣。
echo 1 > myid
4)進入到bin文件夾裏,shift + 右擊,進入控制檯,啓動zookeeper,啓動三個
zkServer.cmd
5)啓動成功後,進入到server1的bin目錄下,連接,連接其他的就進入到相對應的文件夾裏
zkCli.cmd
6)使用set ,ls ,get命令進行測試。在server1中set的數據在server2或者server3中同樣可以看到,保證了同步。
二、使用java連接zookeeper:
首先導入zookeeper-3.4.5的jar到zookeeper項目中,接下來是使用eclipse編寫連接的代碼:
@Test
public void test1() throws Exception{
ZooKeeper zk = new ZooKeeper("localhost:2181", 500000,new Watcher() {
@Override
public void process(WatchedEvent event) {
System.err.println("watch:" + event.toString());
}
});
byte[] data = zk.getData("/", true, null);
System.out.println(data);
}
2181是客戶端連接的端口號,運行的時候我遇到了兩個問題:
1)剛啓動報NoClassDefFoundError錯誤,這個是jar包不全,需要將zookeeper的lib下的log4j和slf4j兩個jar文件導入到項目中,就不會報這樣的錯誤。
2)啓動的時候報這樣的錯誤,連接錯誤。我配置的zookeeper是3個集羣,但是我目前只啓動了一個,在zookeeper中,
啓動的集羣的個數必須大於所有集羣的一半,所以說我這個電腦必須啓動兩個以上的server,才能正常運行。
啓動成功後的效果: