JAVA分布式篇2——Zookeeper
JAVA分布式篇2——Zookeeper
1、簡(jiǎn)介
Zookeeper是一個(gè)開源的分布式(多臺(tái)服務(wù)器干一件事)的,為分布式應(yīng)用提供協(xié)調(diào)服務(wù)的 Apache項(xiàng)目
2、工作機(jī)制
-
Zookeeper從設(shè)計(jì)模式角度來(lái)理解:是一個(gè)基于觀察者模式(一個(gè)人干活,有人盯著他)設(shè)計(jì)的分 布式服務(wù)管理框架
- 存儲(chǔ) 和 管理 大家都關(guān)心的數(shù)據(jù) 然后接受觀察者的注冊(cè)
- 通知已經(jīng)注冊(cè)的那些觀察者做出相應(yīng)的反應(yīng)
-
Zookeeper = 文件系統(tǒng) + 通知機(jī)制
-
類似美團(tuán)
- 商家營(yíng)業(yè)并入駐
- 獲取到當(dāng)前營(yíng)業(yè)的飯店列表
- 服務(wù)器節(jié)點(diǎn)下線
- 服務(wù)器節(jié)點(diǎn)上下線事件通知
- 重新再去獲取服務(wù)器列表,并注冊(cè)監(jiān)聽
3、特點(diǎn)
- 是一個(gè)leader和多個(gè)follower來(lái)組成的集群
- 集群中只要有半數(shù)以上的節(jié)點(diǎn)存活,Zookeeper就能正常工作(5臺(tái)服務(wù)器掛2臺(tái),沒(méi)問(wèn)題;4臺(tái)服 務(wù)器掛2臺(tái),就停止)
- 全局?jǐn)?shù)據(jù)一致性,每臺(tái)服務(wù)器都保存一份相同的數(shù)據(jù)副本,無(wú)論client連接哪臺(tái)server,數(shù)據(jù)都是 一致的
- 數(shù)據(jù)更新原子性,一次數(shù)據(jù)要么成功,要么失敗(不成功便成仁)
- 實(shí)時(shí)性,在一定時(shí)間范圍內(nèi),client能讀取到最新數(shù)據(jù)
- 更新的請(qǐng)求按照順序執(zhí)行,會(huì)按照發(fā)送過(guò)來(lái)的順序,逐一執(zhí)行(發(fā)來(lái)123,執(zhí)行123,而不是321 或者別的)
4、應(yīng)用場(chǎng)景
- 統(tǒng)一命名服務(wù)
- 統(tǒng)一配置管理
- 服務(wù)器節(jié)點(diǎn)動(dòng)態(tài)上下線
- 軟負(fù)載均衡
5、下載安裝(linux)
zookeeper官網(wǎng)下載:https://downloads.apache.org/zookeeper/
zookeeper3.6.3 百度云:https://pan.baidu.com/s/1OM0Lq2rm-8qcd8nb8TGfEg提取碼:izco
linux需要有jdk
移動(dòng)zookeeper
mv /root/apache-zookeeper-3.6.3-bin.tar.gz /usr/local/apache-zookeeper-3.6.3-bin.tar.gz解壓zookeeper
tar -zxvf apache-zookeeper-3.6.3-bin.tar.gzzookeeper目錄下創(chuàng)建文件夾
mkdir zkData mkdir zkLog拷貝配置文件
cp zoo_sample.cfg zoo.cfg vim zoo.cfg添加配置
dataDir=/usr/local/apache-zookeeper-3.6.3-bin/zkData dataLogDir=/usr/local/apache-zookeeper-3.6.3-bin/zkLog啟動(dòng)
[root@VM-16-14-centos bin]# ./zkServer.sh start /usr/bin/java ZooKeeper JMX enabled by default Using config: /usr/local/apache-zookeeper-3.6.3-bin/bin/../conf/zoo.cfg Starting zookeeper ... STARTED測(cè)試
[root@VM-16-14-centos bin]# jps 1898 QuorumPeerMain 1981 Jps [root@VM-16-14-centos bin]# netstat -apn | grep 2181 tcp6 0 0 :::2181 :::* LISTEN 1898/java [root@VM-16-14-centos bin]# ./zkServer.sh status /usr/bin/java ZooKeeper JMX enabled by default Using config: /usr/local/apache-zookeeper-3.6.3-bin/bin/../conf/zoo.cfg Client port found: 2181. Client address: localhost. Client SSL: false. Mode: standalone啟動(dòng)客戶端
[root@VM-16-14-centos bin]# ./zkCli.sh[zk: localhost:2181(CONNECTED) 0] ls ls [-s] [-w] [-R] path [zk: localhost:2181(CONNECTED) 1] ls / [zookeeper] [zk: localhost:2181(CONNECTED) 2] quit6、配置參數(shù)詳解
- tickTime =2000:通信心跳數(shù),Zookeeper服務(wù)器與客戶端心跳時(shí)間,單位毫秒,服務(wù)器之間或客戶端與服務(wù)器之間維持心跳的時(shí)間間隔,也就 是每個(gè)tickTime時(shí)間就會(huì)發(fā)送一個(gè)心跳,時(shí)間單位為毫秒
- initLimit =10:LF初始通信時(shí)限,集群中的Follower跟隨者服務(wù)器與Leader領(lǐng)導(dǎo)者服務(wù)器之間,啟動(dòng)時(shí)能容忍的最多心跳數(shù),10*2000(10個(gè)心跳時(shí)間)如果領(lǐng)導(dǎo)和跟隨者沒(méi)有發(fā)出心跳通信,就視為失效的連接,領(lǐng)導(dǎo) 和跟隨者徹底斷開
- syncLimit =5:LF同步通信時(shí)限,集群?jiǎn)?dòng)后,Leader與Follower之間的最大響應(yīng)時(shí)間單位,假如響應(yīng)超過(guò)syncLimit * tickTime->10秒,Leader就認(rèn)為Follwer已經(jīng)死掉,會(huì)將Follwer從服務(wù)器列表中刪除
- dataDir:數(shù)據(jù)文件目錄+數(shù)據(jù)持久化路徑 主要用于保存Zookeeper中的數(shù)據(jù)
- dataLogDir:日志文件目錄
- clientPort =2181:客戶端連接端口 監(jiān)聽客戶端連接的端口
7、節(jié)點(diǎn)及其類型
7.1、節(jié)點(diǎn)
- ZooKeeper數(shù)據(jù)模型的結(jié)構(gòu)與linux文件系統(tǒng)很類似,整體上可以看作是一棵樹,每個(gè)節(jié)點(diǎn)稱做一 個(gè)ZNode(ZookeeperNode)
- 每一個(gè)ZNode默認(rèn)能夠存儲(chǔ)1MB的數(shù)據(jù)(元數(shù)據(jù)),每個(gè)ZNode的路徑都是唯一的
- 元數(shù)據(jù)(Metadata),又稱中介數(shù)據(jù)、中繼數(shù)據(jù),為描述數(shù)據(jù)的數(shù)據(jù)(data about data),主要是描述數(shù)據(jù)屬性(property)的信息,用來(lái)支持如指示存儲(chǔ)位置、歷史數(shù)據(jù)、 資源查找、文件記錄等功能
7.2、節(jié)點(diǎn)類型
7.2.1、持久型
- 持久化目錄節(jié)點(diǎn)(persistent)客戶端與zookeeper斷開連接后,該節(jié)點(diǎn)依舊存在
- 持久化順序編號(hào)目錄節(jié)點(diǎn)(persistent_sequential)客戶端與zookeeper斷開連接后,該節(jié) 點(diǎn)依舊存在,創(chuàng)建znode時(shí)設(shè)置順序標(biāo)識(shí),znode名稱后會(huì)附加一個(gè)值,順序號(hào)是一個(gè)單調(diào) 遞增的計(jì)數(shù)器,由父節(jié)點(diǎn)維護(hù),例如:Znode001,Znode002…
7.2.2、短暫型
- 臨時(shí)目錄節(jié)點(diǎn)(ephemeral)客戶端和服務(wù)器端斷開連接后,創(chuàng)建的節(jié)點(diǎn)自動(dòng)刪除
- 臨時(shí)順序編號(hào)目錄節(jié)點(diǎn)(ephemeral_sequential)客戶端與zookeeper斷開連接后,該節(jié)點(diǎn) 被刪除,創(chuàng)建znode時(shí)設(shè)置順序標(biāo)識(shí),znode名稱后會(huì)附加一個(gè)值,順序號(hào)是一個(gè)單調(diào)遞增 的計(jì)數(shù)器,由父節(jié)點(diǎn)維護(hù),例如:Znode001,Znode002…
8、分布式部署
8.1、編號(hào)配置
在zkData目錄下書寫myid文件(依次寫上編號(hào)1、2、3)
vim myid8.2、zoo.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=/usr/local/apache-zookeeper-3.6.3-bin/zkData # the port at which the clients will connect clientPort=2181 # the maximum number of client connections. # increase this if you need to handle more clients #maxClientCnxns=60 # # Be sure to read the maintenance section of the # administrator guide before turning on autopurge. # # http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance # # The number of snapshots to retain in dataDir #autopurge.snapRetainCount=3 # Purge task interval in hours # Set to "0" to disable auto purge feature #autopurge.purgeInterval=1## Metrics Providers # # https://prometheus.io Metrics Exporter #metricsProvider.className=org.apache.zookeeper.metrics.prometheus.PrometheusMetricsProvider #metricsProvider.httpPort=7000 #metricsProvider.exportJvmInfo=true #cluster quorumListenOnAllIPs=true server.1=101.34.116.9:2888:3888 server.2=106.54.85.216:2888:3888 server.3=81.70.1.65:2888:3888server.A=B:C:D
- A:一個(gè)數(shù)字,表示第幾號(hào)服務(wù)器(集群模式下配置的/opt/zookeeper/zkData/myid文件里面的數(shù)據(jù)就是A的值)
- B:服務(wù)器的ip地址
- C:與集群中Leader服務(wù)器交換信息的端口
- D:選舉時(shí)專用端口,萬(wàn)一集群中的Leader服務(wù)器掛了,需要一個(gè)端口來(lái)重新進(jìn)行選舉,選 出一個(gè)新的Leader,而這個(gè)端口就是用來(lái)執(zhí)行選舉時(shí)服務(wù)器相互通信的端口
8.3、啟動(dòng)
[root@VM-8-13-centos bin]# ./zkServer.sh start /usr/bin/java ZooKeeper JMX enabled by default Using config: /usr/local/apache-zookeeper-3.6.3-bin/bin/../conf/zoo.cfg Starting zookeeper ... STARTED [root@VM-8-13-centos bin]# jps 29545 QuorumPeerMain 29597 Jps [root@VM-8-13-centos bin]# ./zkServer.sh status /usr/bin/java ZooKeeper JMX enabled by default Using config: /usr/local/apache-zookeeper-3.6.3-bin/bin/../conf/zoo.cfg Client port found: 2181. Client address: localhost. Client SSL: false. Mode: leader [root@VM-0-3-centos bin]# ./zkServer.sh start /usr/bin/java ZooKeeper JMX enabled by default Using config: /usr/local/apache-zookeeper-3.6.3-bin/bin/../conf/zoo.cfg Starting zookeeper ... STARTED [root@VM-0-3-centos bin]# ./zkServer.sh status /usr/bin/java ZooKeeper JMX enabled by default Using config: /usr/local/apache-zookeeper-3.6.3-bin/bin/../conf/zoo.cfg Client port found: 2181. Client address: localhost. Client SSL: false. Mode: follower [root@VM-16-14-centos bin]# ./zkServer.sh start /usr/bin/java ZooKeeper JMX enabled by default Using config: /usr/local/apache-zookeeper-3.6.3-bin/bin/../conf/zoo.cfg Starting zookeeper ... STARTED [root@VM-16-14-centos bin]# jps 29545 QuorumPeerMain 29597 Jps [root@VM-16-14-centos bin]# ./zkServer.sh status /usr/bin/java ZooKeeper JMX enabled by default Using config: /usr/local/apache-zookeeper-3.6.3-bin/bin/../conf/zoo.cfg Client port found: 2181. Client address: localhost. Client SSL: false. Mode: follower8.4、問(wèn)題解決
- 檢查配置文件
- ping一下服務(wù)器
- 查看一下防火墻是否在關(guān)閉狀態(tài)
- 查看防火墻狀態(tài):firewall-cmd --state
- 啟動(dòng)防火墻:systemctl start firewalld
- 關(guān)閉防火墻:systemctl stop firewalld.service
- 禁止防火墻開機(jī)啟動(dòng):systemctl disable firewalld.service
9、客戶端操作
9.1、客戶端啟動(dòng)
./zkCli.sh9.2、幫助
[zk: localhost:2181(CONNECTED) 0] help ZooKeeper -server host:port -client-configuration properties-file cmd argsaddWatch [-m mode] path # optional mode is one of [PERSISTENT, PERSISTENT_RECURSIVE] - default is PERSISTENT_RECURSIVEaddauth scheme authclose config [-c] [-w] [-s]connect host:portcreate [-s] [-e] [-c] [-t ttl] path [data] [acl]delete [-v version] pathdeleteall path [-b batch size]delquota [-n|-b] pathget [-s] [-w] pathgetAcl [-s] pathgetAllChildrenNumber pathgetEphemerals pathhistory listquota pathls [-s] [-w] [-R] pathprintwatches on|offquit reconfig [-s] [-v version] [[-file path] | [-members serverID=host:port1:port2;port3[,...]*]] | [-add serverId=host:port1:port2;port3[,...]]* [-remove serverId[,...]*]redo cmdnoremovewatches path [-c|-d|-a] [-l]set [-s] [-v version] path datasetAcl [-s] [-v version] [-R] path aclsetquota -n|-b val pathstat [-w] pathsync pathversion Command not found: Command not found help9.3、基本命令
#查看當(dāng)前znode中所包含的內(nèi)容 [zk: localhost:2181(CONNECTED) 1] ls / [zookeeper] #查看當(dāng)前節(jié)點(diǎn)詳細(xì)數(shù)據(jù) [zk: localhost:2181(CONNECTED) 2] ls -s / [zookeeper] cZxid = 0x0 ctime = Thu Jan 01 08:00:00 CST 1970 mZxid = 0x0 mtime = Thu Jan 01 08:00:00 CST 1970 pZxid = 0x0 cversion = -1 dataVersion = 0 aclVersion = 0 ephemeralOwner = 0x0 dataLength = 0 numChildren = 1- cZxid:創(chuàng)建節(jié)點(diǎn)的事務(wù) 每次修改ZooKeeper狀態(tài)都會(huì)收到一個(gè)zxid形式的時(shí)間戳,也就是ZooKeeper事務(wù)ID。 事務(wù)ID是ZooKeeper中所有修改總的次序。 每個(gè)修改都有唯一的zxid,如果zxid1小于zxid2,那么zxid1在zxid2之前發(fā)生
- ctime:被創(chuàng)建的毫秒數(shù)(從1970年開始)
- mZxid:最后更新的事務(wù)zxid
- mtime:最后修改的毫秒數(shù)(從1970年開始)
- pZxid:最后更新的子節(jié)點(diǎn)zxid
- cversion:創(chuàng)建版本號(hào),子節(jié)點(diǎn)修改次數(shù)
- dataVersion:數(shù)據(jù)變化版本號(hào)
- aclVersion:權(quán)限版本號(hào)
- ephemeralOwner:如果是臨時(shí)節(jié)點(diǎn),這個(gè)是znode擁有者的session id,如果不是臨時(shí)節(jié)點(diǎn) 則是0
- dataLength:數(shù)據(jù)長(zhǎng)度 numChildren:子節(jié)點(diǎn)數(shù)
10、API
10.1、導(dǎo)入依賴
<dependencies><!--zookeeper--><dependency><groupId>org.apache.zookeeper</groupId><artifactId>zookeeper</artifactId><version>3.6.3</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.14.0</version></dependency><!--junit--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13</version><scope>test</scope></dependency> </dependencies>10.2、創(chuàng)建節(jié)點(diǎn)
public class ZookeeperTest {private String con="101.34.116.9:2181,106.54.85.216:2181,81.70.1.65:2181";//單位毫秒private int time=60*1000;private ZooKeeper zooKeeper;@Beforepublic void zookeeper() throws IOException {Watcher watcher=(watchedEvent)->System.out.println("監(jiān)聽到了變化");zooKeeper = new ZooKeeper(con, time, watcher);}@Testpublic void createNode() throws KeeperException, InterruptedException {String s = zooKeeper.create("/idea", "idea".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);System.out.println(s);} }- 一個(gè)ACL對(duì)象就是一個(gè)Id和permission對(duì)
- 類似linux的文件權(quán)限,不同的是共有5種操作:CREATE、READ、WRITE、DELETE、ADMIN(對(duì)應(yīng)更改ACL的權(quán)限)
- OPEN_ACL_UNSAFE:創(chuàng)建開放節(jié)點(diǎn),允許任意操作 (用的最少,其余的權(quán)限用的很 少)
- READ_ACL_UNSAFE:創(chuàng)建只讀節(jié)點(diǎn)
- CREATOR_ALL_ACL:創(chuàng)建者才有全部權(quán)限
- CreateMode.PERSISTENT:持久型節(jié)點(diǎn)
10.3、查詢節(jié)點(diǎn)
@Test public void selectNode() throws KeeperException, InterruptedException {byte[] data = zooKeeper.getData("/idea", false, new Stat());System.out.println(new String(data)); }10.4、修改節(jié)點(diǎn)
@Test public void updateNode() throws KeeperException, InterruptedException {Stat stat = zooKeeper.setData("/idea", "idea1".getBytes(), 0);System.out.println(stat); } [zk: localhost:2181(CONNECTED) 18] ls -s /idea [] cZxid = 0x100000013 ctime = Thu Jul 29 16:43:11 CST 2021 mZxid = 0x100000013 mtime = Thu Jul 29 16:43:11 CST 2021 pZxid = 0x100000013 cversion = 0 dataVersion = 0 aclVersion = 0 ephemeralOwner = 0x0 dataLength = 4 numChildren = 0 [zk: localhost:2181(CONNECTED) 19] ls -s /idea [] cZxid = 0x100000013 ctime = Thu Jul 29 16:43:11 CST 2021 mZxid = 0x10000001b mtime = Thu Jul 29 17:09:11 CST 2021 pZxid = 0x100000013 cversion = 0 dataVersion = 1 aclVersion = 0 ephemeralOwner = 0x0 dataLength = 5 numChildren = 010.5、刪除節(jié)點(diǎn)
@Test public void deleteNode() throws KeeperException, InterruptedException {zooKeeper.delete("/idea",1); } [zk: localhost:2181(CONNECTED) 21] create /athens Created /athens 監(jiān)聽到了變化 xxx uk0000000004 zookeeper china 監(jiān)聽到了變化10.6、判斷節(jié)點(diǎn)
@Test public void existsNode() throws KeeperException, InterruptedException {Stat exists = zooKeeper.exists("/china", false);System.out.println(exists); }11、監(jiān)聽器
也是美團(tuán)等的工作模式
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來(lái)直接上傳(img-Dj4aI8pH-1627572451887)(C:\Users\yoya\AppData\Roaming\Typora\typora-user-images\image-20210729223559847.png)]
12、分布式鎖
- redis:高性能
- zookeeper:高可用(可靠性)
12.1、傳統(tǒng)鎖
12.2、分布式鎖
12.3、實(shí)現(xiàn)秒殺(ssm)
待補(bǔ)
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的JAVA分布式篇2——Zookeeper的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 英语语法---形容词性从句详解
- 下一篇: mysql++多版本安装_MySQL多版