The foreword 0.

For the convenience of testing, the computer had better be able to run multiple virtual machines, or have 2-3 cloud servers (student machine 9.9 January, you can buy a lightweight and ECS, or borrow a classmate to use)

1. Dubbo vs. SpringCloud

  • Dubbo: ZooKeeper + Dubbo + SpringMVC + Springboot

    • Official address: dubbo.apache.org/#! /? Lang = useful…
    • Supporting communication mode: High RPC performance
    • Registration Center: Zookeper/Redis
    • Configuration center: Diamond (rarely used by enterprises)
  • Springcloud: Family Bucket + Easily embedded third-party components (Netflix)

    • Liverpoolfc.tv: projects. Spring. IO/spring – clou…
    • Communication mode: HTTP restful
    • Registration Centre: Eruka/Consul
    • Configuration center: config
    • Circuit breaker: Hystrix
    • Gateway: zuul
    • Distributed tracking system: Sleuth + Zipkin
  • Comparison of the two:

Dubbo SpringCloud
Service Registry Zookeeper Spring Cloud Netfilx Eureka
Service invocation mode RPC REST API/HTTP
Service monitoring Dubbo-monitor Spring Boot Admin
The circuit breaker imperfect Spring Cloud Netfilx Hystrix
The service gateway There is no Spring Cloud Netfilx Zuul
Distributed configuration There is no Spring Cloud Config
Service tracking There is no Spring Cloud Sleuth
News always stack There is no Spring Cloud Bus
The data flow There is no Spring Cloud Stream
The batch task There is no Spring Cloud Task

Biggest difference: Spring Cloud abandons Dubbo’s RPC communication in favor of HTTP-based REST

Strictly speaking, both approaches have their pros and cons. While the latter compromises the performance of service invocations to some extent, it also avoids the problems of native RPC mentioned above. In addition, REST is more flexible than RPC. The dependence of service providers and callers only depends on a contract, and there is no strong dependence at the code level. This advantage is more appropriate in the current microservice environment that emphasizes rapid evolution.

2. Microservice registry

Introduction: What is a registry and what are the common ones?

  • Registry: service management, the core is a service registry, heartbeat mechanism dynamic maintenance;
  • Service provider: reports its network information to the registry during startup
  • Service consumer: report your network information to the registry when starting, and pull the provider’s network information

Why use a registry?

There are more and more micro-service applications and machines, and the caller needs to know the network address of the interface. If the network address is controlled by configuration files, the maintenance of dynamically added machines will bring great problems!

Mainstream microservice registries

  • Zookeeper (used with Dubbo)
  • Eureka(used in conjunction with SpringCloud)
  • Consul (used in conjunction with SpringCloud)
  • Etcd (used in conjunction with SpringCloud)

3. Download and install Zookeeper

[the Zookeeper’s official website to download address] [zookeeper.apache.org/releases.ht…].

3.1 Installing Zookeeper on CentOS

Note: Installation of Zookeeper depends on the JDK environment! So make sure the server is configured with the JDK environment in the virtual machine first!

  • To upload the zooKeeper package to the cloud server, I put all the packages in ** /usr/local/src/software/* *

    • Tar -zxvf zookeeper-3.4.14.tar.gz Decompress the ZooKeeper package

    • Mv zookeeper-3.4.14 ZooKeeper Change the folder name to Zookeeper to facilitate memory

    • In the mkdir zookeeper directory to create the data catalogue data, and the PWD gain the data directory path * * / usr/local/SRC/software/zookeeper/data * *

    • CD/usr/local/SRC/software/zookeeper/conf to enter the conf directory

      • CFG zoo_sample. CFG Changes the zoo_sample. CFG file name to zoo.cfg

      • Vim zoo. CFG Modify the configuration file. Wq Save the configuration and exit.

    • Useradd zooKeeper Creates a user named zookeeper

    • Chown -r zookeeper:zookeeper zookeeper/ Grant the zooKeeper folder permission to the newly added ZooKeeper user

  • Then we can start the ZooKeeper operation

    • Zookeeper bin directory:

    • / zkserver. sh start Start ZooKeeper.

  • To verify the startup success, let’s connect to the ZooKeeper service using the client:

    • Run the netstat -tlun command to check whether the port service is enabled.

    • It is recommended that you turn off the firewall so that you do not need to add rules to the firewall

    • Ali Cloud security group start port

    • Then we use the zooKeeper client to connect zooKeeper of the server on the local computer (zooKeeper can be used after downloading and decompressing zooKeeper under Windows)

      • .\ zkcli.cmd-timeout 5000-server x.xx.xx. XXX:2181 IP address is the IP address of the server

      • Zookeeper connection completed!

3.2 ZooKeeper Data Model

  • Each node is called a zNode and can have child nodes as well as data
  • Each node can set corresponding permissions to control user access
  • Do not store too much data on each node
  • Each node has a version number that changes when data changes (Optimistic locking)
  • Nodes can be classified into permanent nodes and temporary nodes

4. Common Zookeeper command zkCli

  • Chown -r zookeeper:zookeeper zookeeper/ Grant the zooKeeper folder permission to the ZooKeeper user

  • Su zookeeper Switch to the zooKeeper user

  • Run the./ zkserver. sh start command to start zooKeeper and stop zookeeper. / zkserver. sh stop command

    • If the following error information is displayed, the zooKeeper permission fails to be assigned. Switch to user root and assign the zooKeeper folder permission to user root again:

  • Then you can start successfully:

  • Then we can learn zkCli command:

4.1 zkCli command

  • Start zkCli and run it in the bin directory./zkCli.sh -h
  • Close the zkCli,close
ZooKeeper -server host:port cmd args stat path [watch] set path data [version] ls path [watch] delquota [-n|-b] path ls2  path [watch] setAcl path acl setquota -n|-b val path history redo cmdno printwatches on|off delete path [version] sync path listquota path rmr path get path [watch] create [-s] [-e] path data acl addauth scheme auth quit getAcl path close connect host:portCopy the code

Create and view nodes

  • Create [-s] [-e] path Creates an ACL node

    • -s: creates a sequential node

    • -e: creates a temporary node

    • Data: data content of the created node

  • Look at the node

    • Get the root node: ls /

    • Obtain the child nodes of a node :ls/PATH, eg:ls/CSP0020000000001

    • Get data of a node: get /path

      [zk: Localhost :2181(CONNECTED) 5] GET/cSP0010000000000 CSP001 --> Node value cZxid = 0x5 --> Transaction ID ctime = Wed Nov 18 16:06:18 CST 2020 --> node creation time mZxid = 0x5 --> last update transaction ID mtime = Wed Nov 18 16:06:18 CST 2020 --> last update time pZxid = 0x5 --> The transaction ID of the child node list that was last modified cversion = 0 --> version of the child node list dataVersion = 0 --> Version of the data content aclVersion = 0 --> ACL version ephemeralOwner If the current node is not a temporary node, the value of this field is 0 dataLength = 6 --> Length of data content numChildren = 0 --> Number of child nodesCopy the code
    • View the status of a node: stat /path

      [zk: Localhost :2181(CONNECTED) 4] stat/cSP0020000000001 cZxid = 0x5 --> Ctime = Wed Nov 18 16:06:18 CST 2020 --> MZxid = 0x5 --> Last update transaction ID mtime = Wed Nov 18 16:06:18 CST 2020 --> last update time pZxid = 0x5 --> The transaction ID cversion = 0 --> version of the child node list dataVersion = 0 --> Version of the data content aclVersion = 0 --> ACL version ephemeralOwner = If the current node is not a temporary node, the value of this field is 0 dataLength = 6 --> Length of data content numChildren = 0 --> Number of child nodesCopy the code
    • Gets the status of a node’s children and the current node: ls2 /path

      [zk: Localhost: 2181 (CONNECTED) 6] the create - e/csp0010000000000 csp1999 my name is CSP # add temporary child node to the node Created /csp0010000000000/csp1999 [zk: [CSP1999] # cZxid = 0x4 ctime = Wed Nov 18  16:05:27 CST 2020 mZxid = 0x4 mtime = Wed Nov 18 16:05:27 CST 2020 pZxid = 0xc cversion = 1 dataVersion = 0 aclVersion = 0 ephemeralOwner = 0x0 dataLength = 6 numChildren = 1 [zk: localhost:2181(CONNECTED) 8]Copy the code

Modify the node

  • Modify node data: set /path data [version]

    [zk: localhost:2181(CONNECTED) 10] set /csp0010000000000 HelloWorld cZxid = 0x4 ctime = Wed Nov 18 16:05:27 CST 2020 mZxid = 0xD mTime = Wed Nov 18 16:28:10 CST 2020 pZxid = 0xC CVersion = 1 DatSpanning = 1 # DatSpanning from 0 to 1 aclVersion = 0 ephemeralOwner = 0x0 dataLength = 10 numChildren = 1 [zk: localhost:2181(CONNECTED) 11] get /csp0010000000000 HelloWorld cZxid = 0x4 ctime = Wed Nov 18 16:05:27 CST 2020 mZxid = 0xD mTime = Wed Nov 18 16:28:10 CST 2020 pZxid = 0xC CVersion = 1 DatSpanning = 1 # DatSpanning from 0 to 1 aclVersion = 0 ephemeralOwner = 0x0 dataLength = 10 numChildren = 1
    #Datspanning is the equivalent of optimistic locks in MySQL, the version numbers of data
    #ifsetThe version command is used to modify node data. If the version does not match, the version cannot be modified.
    #Such as:[zk: localhost:2181(CONNECTED) 12] set /csp0010000000000 HelloWorld 0 version No is not valid : /csp0010000000000 # version does not match, cannot be changed [zk: localhost:2181(CONNECTED) 13] set /csp0010000000000 HelloWorld 2 version No is not valid : /csp0010000000000 # version does not match, cannot be changed [zk: Localhost :2181(CONNECTED) 14] set/cSP0010000000000 HelloWorld cZxid = 0x4 ctime = Wed Nov 18 16:05:27 CST 2020 mZxid = 0x10 mtime = Wed Nov 18 16:33:34 CST 2020 pZxid = 0xc cversion AclVersion = 0 ephemeralOwner = 0x0 dataLength = 10 numChildren = 1Copy the code

Remove nodes

  • delete /path [version]Non-recursive deletion
  • rmr /path [version]Recursive delete
[zk: localhost:2181(CONNECTED) 15] ls / [csp0010000000000, csp0040000000003, zookeeper, csp0020000000001, Csp0030000000002] [zk: localhost:2181(CONNECTED) 16] delete /csp0030000000002 Localhost :2181(CONNECTED) 17] ls / [cSP0010000000000, CSP0040000000003, Zookeeper, cSP0020000000001] [zk: localhost:2181(CONNECTED) 18] delete /csp0010000000000 /csp0010000000000 # This node has child nodes, delete failed! [zk: CONNECTED) 19] RMR /csp0010000000000 Localhost :2181(CONNECTED) 20] ls / [cSP0040000000003, Zookeeper, cSP0020000000001]Copy the code

5. Session mechanism and Watcher mechanism in Zookeeper

5.1 Session Mechanism in Zookeeper

  • For the connection between the client and the server, you can set the timeout period. If the heartbeat packet mechanism (the client pings the heartbeat packet request from the server) is used to check that the heartbeat is over, the session expires
  • When a session expires, all temporary nodes created by that session are discarded

5.2 Watcher mechanism in Zookeeper

  • Run the get/stat + watch command on the watcher of a node

    For each node operation, there can be a monitor. When the node changes, the Watcher event will be triggered. In ZK, the Watcher event is one-off, and the change operation of all nodes with monitors will be destroyed immediately after the trigger

    • Why is the Watch incident a one-off? Take a look at the actual operation:

      Which of the previous clients printed the result:

  • The watcher operation on the child node (monitor the parent node, and the watcher event on the parent node will be triggered when the child node corresponding to the parent node changes) ls/ LS2 + Watch will be triggered, but the modification will not be triggered. If the child node adds a child node, it will not be triggered (i.e., The watcher event must be triggered by a direct descendant node.

6. ACL permission control in Zookeeper

  • You can set read and write permissions for nodes to ensure data security

  • Permissions You can specify different permission scopes and roles

  • Common Commands

    • GetAcl Obtains node permissions
    • SetAcl Sets the node permission
    • Addauth: enter the authentication and authorization information. Enter the plaintext password for registration, but in ZK, it is saved in encrypted form
    [zk: localhost:2181(CONNECTED) 3] rmr /csp0001 [zk: localhost:2181(CONNECTED) 4] create /csp0001 HelloWorld Created /csp0001 [zk: Localhost :2181(CONNECTED) 5] getAcl/cSP0001Copy the code
  • **[Scheme: id:permissions]**

  • Scheme Authorization Mechanism

    • worldThere’s only one ID underneath, which is thetaanyoneAll of usworld:anyone:permissions
    • authOn behalf of authentication login, the registered user must have permissionauth:user:password:permissions
    • digestPassword encryption is required to accessdigest:username:BASE64(SHA1(password)):permissions(Auth is different from Auth because auth is in clear text and digest is ciphertext.)
    • IP, such as:ip:localhost:psermissions
    • Super stands for supermanage, having all permissions;
    • Open the /bin/zkserver. sh server script file in the Zk directory and find the following line:
  • Id: indicates the user that is allowed to access

  • Permissions: a string of permission combinations

    Cdrwa: c --> create Creates a child node D --> delete Deletes a child node R --> Read Reads data on a node W --> Write Writes data A --> Admin Manages permissions cdrWA CDR CDWCopy the code
  • Acls are used in the following scenarios:

  • The development environment can be separated from the test environment by using acl. The developer has no right to operate the test node. In the production environment, the service controlling the specified IP address can access the related node

7. Three roles and their election mechanism in Zookeeper

7.1 Three roles and their functions

  • Leader: Serves as the sole handler of write requests for the entire ZK cluster and is responsible for initiating and deciding votes and updating system status.
  • Follower: receives client requests, processes read requests, and returns results to the client. Forward the write request to the Leader; Vote in the election of Leader.
  • Observer: can be understood as a non-voting Flollower, which is designed to help followers process more read requests. If the Zookeeper cluster has a high load of read requests, or if there are many, many clients that span the machine room, you can set up some Observer servers to improve read throughput.

7.2 Three common modes for a registry

  • The core of ZK is the broadcast mechanism, which ensures the data synchronization (data consistency) between ZKS. The mechanism implemented by ZK is ZAB protocol
  • Recovery mode: If the leader crashes, it goes into recovery mode, bringing the entire ZK cluster back to normal working state
  • Synchronization mode: After a new leader is elected, the new leader enters the synchronization mode (each follower synchronizes data from the new leader). The recovery mode ends when most ZKServers have completed state synchronization with the leader
  • Broadcast mode: When the client wants to write data, the leader initiates a proposal. After the leader’s proposal is unified by most ZKServers, the leader modifies his own data and broadcasts the modified data to other followers

7.3 Election Mechanism of Zookeeper

  • myid

    This is the unique identity of the server in the ZK cluster and is called myID. For example, if there are three ZK servers, the numbers are 1,2, and 3 respectively.

  • zxid

    ReentranReadWriteLock 32Bit high low0000000000000000  0000000000000000
    
                       epoch                                 xid
    00000000000000000000000000000000   00000000000000000000000000000000The zxID is of the type Long, with the medium height32Bit means epoch, low32Bits represent xID. That is, the ZXID consists of two parts: epoch and XID. Each Leader will have a different epoch value, representing a period or era. When a new Leader is created, the epochs in the ZXids of all ZKServers will be updated. Xid is the transaction ID of ZK. Each write operation is a transaction and has an XID. Each write operation requires a proposal from the Leader, and all followers vote on whether to approve the write operation.Copy the code
  • The logical clock

    The Logicalclock, Logicalclock, is an integer. The concept is called Logicalclock at election time and the value of epoch in zxid. That is, epoch and logicalClock are the same value, but different names in different cases.

  • Election status of ZK

    LOOKING, election status (find the status of the Leader). LEADING, leader status. The server in this state is called the Leader. FOLLOWING, follower state, synchronization leader state. The server in this state is called Follower. OBSERVING: indicates the OBSERVING state. Synchronization: indicates the leader state. The server in this state is called an Observer.Copy the code

8. Set up the Zookeeper cluster

First of all, I prepared three Aliyun servers (if there are no servers, you can consider cloning 3 local virtual machines) :

Then follow the steps in Section 3 to set up the ZooKeeper environment for the other two servers!

Note: When building the ZooKeeper cluster, do not forget to open the corresponding ports of ali Cloud server security group!

  • Functions of ports

    • 2181 Provides services for the client
    • 2888 Port used for communication within the cluster
    • 3888 The cluster elects a leader
  • Modify zK configurations of the three servers

    • Go to the zookeeper conf directory and modify zoo. CFG. Add the following information:

      dataDir=/usr/local/src/software/zookeeper/data
      # the port at which the clients will connect
      clientPort=2181
      server.1=8.XXX.XX.136:2182:2183
      server.2=8.XXX.XX.45:2182:2183
      server.3=39.XXX.XXX.61:2182:2183
      Copy the code
    • In the root directory of zK, create a data directory and add a myID file to the data directory

    • Zk will modify good configuration, respectively in the three servers * * / usr/local/SRC/software/zookeeper * *, and change the directory permissions to zookeeper users

    • Add user useradd ZooKeeper for each of the three servers

    • Three servers, all changes * * / usr/local/SRC/software/zookeeper/data / * * the myid files in the directory, file content is a number, the corresponding server. 1 = 8. XXX. XX. 136:2182-2183 in 1 and so on!

    • The ZOOkeeper user chown -r zookeeper:zookeeper zookeeper/ has been assigned the ZOOkeeper permission for the three servers

    • Run the systemctl stop firewalld.service command to disable the firewall

    • Go to the bin directory of the ZK: rm -rf *. CMD, then chmod +x *.sh

    • Run the./ zkserver. sh start command to start the ZooKeeper service on the first PC

    • After all three servers are started, run the zkserver. sh status command to check the status

    View the result as shown below:

    In this way, a cluster of three Ali cloud servers, one leader and two followers has been built!

    Hit the pit:

    If the following error occurs when you run ZooKeeper:./zkServer status

    Check out this article: blog.csdn.net/kenneth_che…

Zookeeper cluster Setup is another reference article

If this article is helpful to you, please give it a thumbs up