Zookeeper yes Apache A distributed service framework
It is mainly used to solve some data management problems often encountered in distributed applications , as : Unified naming service , State synchronization service , Cluster management , Management of distributed application configuration items, etc
In short zookeeper= file system + Monitoring notification mechanism

<> storage structure

stay ZooKeeper in ,znode It's one with Unix Nodes with similar file system paths , Data can be stored or obtained from nodes .Zookeeper
The bottom layer is a set of data structures . This storage structure is a tree structure , Every node on it , We call it “znode” Zookeeper The data in is in accordance with “ tree ” Structure for storage . and
znode Nodes are also divided into 4 Different in Type of . every last znode It can be stored by default 1MB Data **( For data recording the nature of the state , Enough )**

<>Znode Node type

* PERSISTENT- Persistent directory node : Client and zookeeper After disconnection , The node still exists
* PERSISTENT_SEQUENTIAL- Persistent sequence number directory node : stay PERSISTENT Based on nodes , The node name is also numbered sequentially
* EPHEMERAL- Temporary directory node : Client and zookeeper After disconnection , The node is deleted
* EPHEMERAL-SEAUENTIAL- Temporary directory node in EPHEMEEAL Based on nodes , The node name is also numbered sequentially
<> Monitoring notification mechanism

ZooKeeper It is designed using the observer design pattern
When the client registers to listen to the directory node it cares about , When the directory node changes ( Data change , Deleted , Add and delete subdirectory nodes ) Time ,ZooKeeper The client will be notified

<> install ZooKeeper

in use ZooKeeper before ,Linux The system needs to have jdk environment , I won't repeat it here .
[root@localhost temp]# tar -zxf zookeeper-3.6.0.tar.gz [root@localhost temp]#
cp zookeeper-3.6.0 /usr/local/zookeeper -r
<>ZooKeeper directory structure

* bin: Place and run scripts and tool scripts
* conf:zookeeper There will be a default configuration file in the directory of the default read configuration
* docs:zookeeper Related documents
* lib:zookeeper Core jar
* logs:zookeeper journal
* data:zookeeper Location of data storage , But you need to create it yourself
<> to configure ZooKeeper

ZooKeeper Default at startup conf Find a directory named zoo.cfg Configuration file for . however conf This file is not in the directory , only zoo_sample.cfg, seeing the name of a thing one thinks of its function , That's what we're looking for zoo.cfg Template for file . We need to configure based on this file zoo.cfg
cp zoo_sample.cfg zoo.cfg vim zoo.cfg

Among them

* datadir:data Absolute path of the folder , According to their own needs data Modify the actual path of
* clientPort: Port number to listen on , Default is 2181, single zookeeper No modification is required
<> start-up ZooKeeper

The following orders are bin Execute under directory

* Default load profile :./zkServer.sh start: Will go by default conf Load under directory zoo.cfg configuration file
* Specify load profile :./zkServer.sh start Path to configuration file
<> stop it ZooKeeper

./zkServer.sh stop

<> see ZooKeeper state

./zkServer.sh status

<> Use client to connect to stand-alone

* ./zkClient.sh: The default connection address is the local address , Default port 2181
* ./zkClient.sh -server ip:port: Connection assignment ip And port
The functions realized in the first way are realized in the second way : ./zkClient.sh -server
<>ZooKeeper colony

<>ZooKeeper Roles in clusters

* leader: Be responsible for finding, voting and resolution , Update system status
* follower:Follower It is used to receive customer requests and return results to the client , Vote in the election process
* observer:Observer Can receive client connections , Forward write request to leader node . but Observer Not participating in the voting process , Sync only leader State of .
Observer The purpose of is to expand the system , Improve reading speed
* client: Request originator
<> Cluster installation

Create a zookeepercluster folder , Then make three copies zookeeper, as follows

Modify three zookeeper of zoo.cfg file , as follows :


* datadir Enter the corresponding data route
* clientPort: Because there are three zookeeper, So fill in separately 2181,2182,2183 that will do
* server part :server. identification :ip:2881:2883, There are several zookeeper Just fill in a few lines , But different zoo.cfg The files are the same
be careful :server. identification : The following logo represents different zookeeper file , Therefore, when different clusters are needed zookeeper of data Create in myid file , as follows :

Shortcut method :
stay zookeepercluster Under path
echo 1 >> zookeeper01/data/myid echo 2 >> zookeeper02/data/myid echo 3 >>
1,2,3 It corresponds to the logo in my screenshot , If there is no corresponding myid, Automatically created myid
here , One zookeeper The cluster is configured .
But it takes one by one zookeeper start-up , One by one zookeeper Isn't it troublesome . For less trouble , We can write these orders as sh file
vim startall.sh
Then write these commands in

input :wq preservation
Similarly , We can also write one shutdown.sh File stop zookeeper function

But in this case , this sh The file cannot be executed yet , Then use it liunx Command to add permissions to it
chomd 777 startall.sh chomd 777 shutdown.sh
It's done now .

<> Start cluster

<> Shut down the cluster

<> Connection cluster

You can use any client connection
./zkClient -server
<>ZooKeeper Common commands

* ls: View child nodes ls /path
use ls Command view zookeeper Content in . stay ZooKeeper Console client , There is no default list can , You must specify a location to list resources

* create: establish Znode node create [-e] [-s] /path [data]
plus -e Indicates a temporary node ,-s Indicates that it needs to be numbered ,/path Represents the node to create ,data Represents the value of the node , Above band [] All represent optional parameters

* get: Get the value of the corresponding node get [-s] /path
-s Indicates whether to view details

* set: Add or modify the value of a node set /path [data]
* delete: Delete node delete /path
<>Java operation ZooKeeper

add to pom rely on
<dependency> <groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId> <version>3.6.0</version> </dependency> public
class ZnodeDemo implements Watcher { public static void main(String[] args)
throws InterruptedException, KeeperException, IOException { ZooKeeper zooKeeper
= new ZooKeeper(",,"
,150000,new ZnodeDemo()); // establish Znode String path = zooKeeper.create("/lanh/try",
"ni".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
System.out.println(path); // Gets the data of the specified node byte[] data = zooKeeper.getData(
"/lanh/try0000000002",new ZnodeDemo(),new Stat()); System.out.println(new String
(data)); // Gets the data in all child nodes in the specified node List<String> list = zooKeeper.getChildren("/lanh",
new ZnodeDemo()); for (String s:list){ System.out.println(new String(zooKeeper.
getData("/lanh/"+s,new ZnodeDemo(),new Stat()))); } // Set node value ,-1 Indicates all versions Stat stat =
zooKeeper.setData("/lanh/try0000000002","get it a try".getBytes(),-1); System.
out.println(stat); // Delete node value zooKeeper.delete("/lanh/try0000000001",-1); }
@Override public void process(WatchedEvent watchedEvent) { if(watchedEvent.
getState()==Event.KeeperState.SyncConnected){ System.out.println(" Connection successful "); } } }
<> use Zookeeper Implemented as a registry RPC

<>RMI of API introduce

* Remote Interface
java.rmi.Remote This interface is defined as a remote call interface , If the interface is called externally , Need to inherit this interface
* RemoteException class
java.rmi.RemoteException class
Inherited Remote Interface of interface , If the method is allowed to be called remotely , This exception needs to be thrown
* UnicastRemoteObject class
This class implements Remote Interface and Serializable Interface
User defined interface implementation class in addition to implementing user-defined interface , You also need to inherit this class
* LocateRegistry
Can pass LocateRegistry, This can be accessed through a specific port Registry
* Naming class
Naming Defines the accessibility of published content RMI name . Also through Naming Gets the specified remote method
<>pom rely on
<dependency> <groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId> <version>3.6.0</version> </dependency>
<> Custom interface
import java.rmi.Remote; import java.rmi.RemoteException; public interface
UsersService extends Remote { String findUsers(String str) throws
RemoteException; }
<> Custom interface implementation class
import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject;
/** * @Author Lanh **/ public class UsersServiceImpl extends UnicastRemoteObject
implements UsersService { public UsersServiceImpl() throws RemoteException { }
public String findUsers(String str) throws RemoteException { return "Hello
zookeeper "+str; } }
<> Server
import org.apache.zookeeper.*; import java.io.IOException; import java.rmi.
AlreadyBoundException; import java.rmi.Naming; import java.rmi.registry.
LocateRegistry; /** * @Author Lanh **/ public class ServerDemo implements
Watcher { public static void main(String[] args) throws IOException,
AlreadyBoundException, InterruptedException, KeeperException { UsersService
usersService= new UsersServiceImpl(); LocateRegistry.createRegistry(8888);
String url = "rmi://localhost:8888/user"; Naming.bind(url,usersService);
// take url Information put Znode in ZooKeeper zooKeeper = new ZooKeeper(
ServerDemo()); zooKeeper.delete("/lanh/service",-1); zooKeeper.create(
); System.out.println(" Service published successfully "); } public void process(WatchedEvent watchedEvent
) { if (watchedEvent.getState()==Event.KeeperState.SyncConnected){ System.out.
println(" Connection successful "); } } }
<> Client module

There should also be corresponding interfaces
package com.lanh.service; public interface UsersService{ String findUsers(
String str); } import org.apache.zookeeper.KeeperException; import org.apache.
zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.
zookeeper.ZooKeeper; import java.io.IOException; import java.rmi.Naming; import
java.rmi.NotBoundException; /** * @Author Lanh **/ public class ClientDemo
implements Watcher { public static void main(String[] args) throws IOException,
NotBoundException, InterruptedException, KeeperException { ZooKeeper zooKeeper =
new ZooKeeper(",,",
150000,new ClientDemo()); byte[] bytes = zooKeeper.getData("/lanh/service",new
ClientDemo(),null); String url = new String(bytes); UsersService usersService =
(UsersService) Naming.lookup(url); String result = usersService.findUsers("Lanh"
); System.out.println(result); } public void process(WatchedEvent watchedEvent)
{ if (watchedEvent.getState()==Event.KeeperState.SyncConnected){ System.out.
println(" Connection successful "); } } }
This is the end , You are also welcome to discuss

©2019-2020 Toolsou All rights reserved,
C++ of string of compare usage MySQL Basics Commonly used sentence ( Add / delete / modify query )C Language of a Gobang game implementation QT5.9 Use of learning notes QSqlQuery Method of Qt Getting Started tutorial 【 Basic controls 】QCalendarWidget calendar control java Polymorphic array of web Front end signature plug-in _signature_pad Plug in implements electronic signature function centos7 install RabbitMqspringboot use redis Experiment 4 Automated test tools - software test