Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the basic usage of Dubbo and ZooKeeper

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "what is the basic usage of Dubbo and ZooKeeper". Friends who are interested may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the basic usage of Dubbo and ZooKeeper"?

First, transform the background

In modern distributed applications, there are often problems of coordination between nodes, including: selection, cluster management, distributed lock, distributed configuration management, unified naming service, state synchronization and so on. Apache ZooKeeper, as its name implies, zookeepers, is a distributed coordination service framework to address these demands.

In order to ensure the high availability of the system, ZooKeeper itself can also be deployed as a cluster mode, called ZooKeeper Ensemble. Always ensure that one of the ZooKeeper clusters is the role of leader, and ensure that the information on all nodes is consistent through the ZAB (Zookeeper Atomic Broadcast Protocol) [1] protocol. The client can access any station in the cluster for read and write operations without worrying about data inconsistencies.

Ebook-Zookeeper-Distributed Process Coordination of O'Reilly

The way of data storage in ZooKeeper is similar to that of traditional UNIX file system. Nodes are organized according to a tree structure, in which nodes are called znodes (ZooKeeper data nodes).

II. Basic usage

ZooKeeper can be installed and run through direct download [2], and it can also be installed on Mac through Homebrew [3] brew install zookeeper. Considering the versatility, this paper uses docker to run ZooKeeper. If you do not have docker installed, prepare the docker environment [4] first.

1. Start ZooKeeper

Execute the command to run ZooKeeper in the docker container.

Docker run-- rm-- name zookeeper-p 2181 zookeeper

2. Enter the Zookeeper container

Docker exec-it zookeeper bash

In the bin directory, there are commands to start ZooKeeper, zkServer and administrative console zkCli.

Bash-4.4# ls-l bintotal 36-rwxr-xr-x 1 zookeepe zookeepe 32 Mar 27 04:32 README.txt-rwxr-xr-x 1 zookeepe zookeepe 1937 Mar 27 04:32 zkCleanup.sh-rwxr-xr-x 1 zookeepe zookeepe 1056 Mar 27 04:32 zkCli.cmd-rwxr-xr-x 1 zookeepe zookeepe 1534 Mar 27 04:32 zkCli.sh-rwxr-xr-x 1 zookeepe zookeepe 1759 Mar 27 04:32 zkEnv.cmd-rwxr- Xr-x 1 zookeepe zookeepe 2696 Mar 27 04:32 zkEnv.sh-rwxr-xr-x 1 zookeepe zookeepe 1089 Mar 27 04:32 zkServer.cmd-rwxr-xr-x 1 zookeepe zookeepe 6773 Mar 27 04:32 zkServer.sh``

3. Enter the Zookeeper management interface through zkCli

Since it was started through Docker, the ZooKeeper process has been started and services are provided through port 2181.

Bash-4.4# psPID USER TIME COMMAND1 zookeepe 0:02 / usr/lib/jvm/java-1.8-openjdk/jre/bin/java-Dzookeeper.log.dir=. -Dzookeeper.root 32 root 0:00 bash 42 root 0:00 ps

Therefore, you can access the console of ZooKeeper directly through zkCli for management.

Bash-4.4# bin/zkCli.sh-server 127.0.0.1:2181Connecting to 127.0.0.1:2181...WATCHER::WatchedEvent state:SyncConnected type:None path:null [zk: 127.0.0.1 CONNECTED 2181 (CONNECTED) 0] helpZooKeeper-server host:port cmd args stat path [watch] set path data [version] ls path [watch] delquota [- n |-b] pathls2 path [watch] setAcl path aclsetquota-n |-b val path historyredo cmdnoprintwatches on | offdelete path [version] sync Pathlistquota pathrmr pathget path [watch] create [- s] [- e] path data acladdauth scheme authquitgetAcl pathcloseconnect host:port

Some basic operations on 4.zkCli

Create a / hello-zone node:

[zk: 127.0.0.1 create 2181 (CONNECTED) 19] create / hello-zone 'world'Created / hello-zone

List the child nodes under / and confirm that the hello-zone is created:

[zk: 127.0.0.1 create 2181 (CONNECTED) 19] create / hello-zone 'world'Created / hello-zone

List the child nodes of / hello-zone and confirm to be empty:

[zk: 127.0.0.1 ls 2181 (CONNECTED) 21] ls / hello-zone []

Get the data stored on the / hello-zone node:

[zk: 127.0.0.1 get 2181 (CONNECTED) 22] get / hello-zoneworld III. Use ZooKeeper in Dubbo

Dubbo uses ZooKeeper for registration discovery and configuration management of services:

First, all Dubbo-related data is organized under the root node of / duboo.

The secondary directory is the service name, such as com.foo.BarService.

The third-level directory has two child nodes, providers and consumers, which represent the provider and consumer of the service.

The four-level directory records the URL information of each application instance related to the service, representing all providers of the service under providers and all consumers of the service under consumers. For example, the service provider of com.foo.BarService registers its URL information under / dubbo/com.foo.BarService/providers at startup; similarly, service consumers register their information under the corresponding consumers, and at the same time, service consumers subscribe to their corresponding providers node so that they can be aware of changes in the address list of service providers.

Fourth, prepare the sample code

The code for this article can be found in the link below.

1. Interface definition

A simple GreetingService interface with only a simple method, sayHello, to say hello to the caller.

Public interface GreetingService {String sayHello (String name);}

2. Server: service implementation

Implement the GreetingService interface and mark it as a service of Dubbo through @ Service.

@ Servicepublic class AnnotatedGreetingService implements GreetingService {public String sayHello (String name) {return "hello," >

3. Server: Assembly

Define ProviderConfiguration to assemble Dubbo services.

@ Configuration@EnableDubbo (scanBasePackages = "com.alibaba.dubbo.samples.impl") @ PropertySource ("classpath:/spring/dubbo-provider.properties") static class ProviderConfiguration {}

Dubbo-provider.properties is a way to apply external configuration in Spring, as follows:

Dubbo.application.name=demo-providerdubbo.registry.address=zookeeper://$DOCKER_HOST:2181dubbo.protocol.name=dubbodubbo.protocol.port=20880

Because ZooKeeper runs in a Docker container, it is important to note that:

This article assumes that the Dubbo application runs on the host, that is, outside the Docker container, and needs to replace the address of ZooKeeper with the IP address specified by the environment variable ${DOCKER_HOST}. For more information, please refer to the official Docker documentation.

If the Dubbo application is also a dockerized application, you only need to use the container name of ZooKeeper, which in this article is ZooKeeper.

Of course, if you don't start ZooKeeper in a container way, simply change the $DOCKER_HOST here to localhost.

4. Server: start the service

In the main method, the Dubbo service is provided by launching a Spring Context.

Public class ProviderBootstrap {public static void main (String [] args) throws Exception {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext (ProviderConfiguration.class); context.start (); System.in.read ();}}

The main method of the service initiator will see the following output, indicating that the server has successfully started and registered the GreetingService service with the registry (ZooKeeperRegistry):

[03/08/18 10:50:33:033 CST] main INFO zookeeper.ZookeeperRegistry: [DUBBO] Register: dubbo://192.168.99.1:20880/com.alibaba.dubbo.samples.api.GreetingService?anyhost=true&application=demo-provider&dubbo=2.6.2&generic=false&interface=com.alibaba.dubbo.samples.api.GreetingService&methods=sayHello&pid=12938&side=provider×tamp=1533264631849, dubbo version: 2.6.2, current host: 192.168.99.1

Observe the registration information of the service provider through the ZooKeeper management terminal:

$docker exec-it zookeeper bashbash-4.4# bin/zkCli.sh-server localhost:218Connecting to localhost:2181...Welcome to ZooKeePerforming JLine support is enabled... [zk: localhost:2181 (CONNECTED) 0] ls [dubbo%3A%2F%2F192.168.99.1%3A20880%2Fcom.alibaba.dubbo.samples.api.GreetingService%3Fanyhost%3Dtrue%26application%3Ddemo-provider%26dubbo%3D2.6.2%26generic%3Dfalse%26interface%3Dcom.alibaba.dubbo.samples.api.GreetingService%26methods%3DsayHello % 26pid%3D12938%26side%3Dprovider%26timestamp%3D1533264631849]

You can see that the Dubbo service that you just started has registered its URL address under the providers node: dubbo://192.168.99.1:20880 / com.alibaba.dubbo.samples.api.GreetingService? Anyhost = true&application = demo-provider&dubbo = 2.60.2 & generic = pseudo interface = com.alibaba.dubbo.samples.api.GreetingService& method = sayHello & PID = 12938 & side = provider timestamp = 1533264631849

5. Client: reference service

Using @ Reference to declare a reference to the service on the client, the runtime will make a full call through this reference, and the target address of the service will be queried from the provider node of the ZooKeeper.

@ Component ("annotatedConsumer") public class GreetingServiceConsumer {@ Referenceprivate GreetingService greetingService;public String doSayHello (String name) {return greetingService.sayHello (name);}}

6. Client: Assembly

Define ConsumerConfiguration to assemble Dubbo services.

@ Configuration@EnableDubbo (scanBasePackages = "com.alibaba.dubbo.samples.action") @ PropertySource ("classpath:/spring/dubbo-consumer.properties") @ ComponentScan (value = {"com.alibaba.dubbo.samples.action"}) static class ConsumerConfiguration {}

Dubbo-consumer.properties is a way to apply external configuration in Spring, as follows:

Dubbo.application.name=demo-consumerdubbo.registry.address=zookeeper://$DOCKER_HOST:2181dubbo.consumer.timeout=3000

Same as the server-side assembly, you need to modify the $DOCKER_HOST defined in dubbo.registry.address according to your own running environment. See the description section of step 3.

7. Client: initiate a remote call

Run main to make a remote call to the service provider that is already started. Dubbo subscribes the service address to ZooKeeper, then selects one from the returned address list and initiates a call to the peer:

Public class ConsumerBootstrap {public static void main (String [] args) {public class ConsumerBootstrap {public static void main (String [] args) throws IOException {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext (ConsumerConfiguration.class); context.start (); GreetingServiceConsumer greetingServiceConsumer = context.getBean (GreetingServiceConsumer.class); String hello = greetingServiceConsumer.doSayHello ("zookeeper"); System.out.println ("result:" + hello); System.in.read ();}}

The running results are as follows:

[03/08/18 01:42:31:031 CST] main INFO zookeeper.ZookeeperRegistry: [DUBBO] Register: consumer://192.168.99.1/com.alibaba.dubbo.samples.api.GreetingService?application=demo-consumer&category=consumers&check=false&default.timeout=3000&dubbo=2.6.2&interface=com.alibaba.dubbo.samples.api.GreetingService&methods=sayHello&pid=82406&side=consumer×tamp=1533274951195, dubbo version: 2.6.2 Current host: 192.168.99.1 # 1 [03/08/18 01:42:31:031 CST] main INFO zookeeper.ZookeeperRegistry: [DUBBO] Subscribe: consumer://192.168.99.1/com.alibaba.dubbo.samples.api.GreetingService?application=demo-consumer&category=providers,configurators,routers&default.timeout=3000&dubbo=2.6.2&interface=com.alibaba.dubbo.samples.api.GreetingService&methods=sayHello&pid=82406&side=consumer×tamp=1533274951195, dubbo version: 2.6.2, current host: 192.168.99.1 # 2...

Result: hello, zookeeper

Description:

Registration: consumer: / / 192.168.99.1 category= consumers&: consumers register their information with ZooKeeper and put it under the consumers node

Subscription: consumer: / / 192.168.99.1 providers. & Category = provider, Configurator, Router: consumers also subscribe to providers, configurators, routers nodes from zoo keepers, where configurations is related to Dobo configuration, routers is related to routing rules, noteworthy English providers node subscription, when a new service provider joins, due to subscription, the new address list will be pushed to the subscriber As a result, consumers of the service are dynamically aware of the change in the address list.

Observe the registration information of the service provider through the ZooKeeper management terminal:

$docker exec-it zookeeper bashbash-4.4# bin/zkCli.sh-server localhost:218Connecting to localhost:2181...Welcome to ZooKeePerforming JLine support is enabled... [zk: localhost:2181 (CONNECTED) 4] ls / dubbo/com.alibaba.dubbo.samples.api.GreetingService/consumers [consumer%3A%2F%2F192.168.99.1%2Fcom.alibaba.dubbo.samples.api.GreetingService%3Fapplication%3Ddemo-consumer%26category%3Dconsumers%26check%3Dfalse%26default.timeout%3D3000%26dubbo%3D2.6 .2% 26interface% 3Dcom.alibaba.dubbo.samples.api.GreetingService% 26methods% 3DsayHelo% 26pid% 3D82406% 26side3D worker% 26timestamp% 3D1533274951195]

You can see that the service consumer of Dubbo has registered their URL address under the consumers node:

Consumer://192.168.99.1/com.alibaba.dubbo.samples.api.GreetingService?application=demo-consumer&category=providers,configurators,routers&default.timeout=3000&dubbo=2.6.2&interface=com.alibaba.dubbo.samples.api.GreetingService&methods=sayHello&pid=82406&side=consumer×tamp=1533274951195

At this point, I believe you have a deeper understanding of "what is the basic usage of Dubbo and ZooKeeper". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report