How to realize the unified contract in Dubbo?

Time:2021-4-8

Write on the front

Before, many small partners wrote to me: how to quickly master the core principles and source code of Dubbo. So, I wrote an article《How can I quickly master the principle and source code of Dubbo (pure dry goods) in a short time?》。 For Dubbo’s source code analysis series articles, I am also thinking about how to make the source code analysis articles easier to understand. Therefore, I adjusted the strategy of writing Dubbo’s source code analysis articles, and strive to let my friends thoroughly master Dubbo’s source code in a simpler and easier way. Today, let’s talk about how the unified contract in Dubbo is realized.

The article has been included in:

https://github.com/sunshinelyz/technology-binghe

https://gitee.com/binghe001/technology-binghe

Have to say URL

The full name of URL is uniform resource locator, which can locate a unique network address in the Internet. The format of the URL is as follows.

protocol://username:[email protected]:port/path?key=value&key=value

The brief description of each part is as follows.

  • Protocol: the protocol of the URL. The most common protocols are HTTP and HTTPS, and others are FTP, WS, file, SMTP, etc.
  • User name: user name.
  • Password: password.
  • Host: host, usually domain name or IP address.
  • Port: the port number of the host.
  • Path: the path of the requested target file.
  • Parameters: the specific parameter information of the request, here key = value & key = value.

This is a simple description of the URL in our Internet.

In Dubbo, a large number of parameters received by methods are encapsulated by URLs. What role does URL play in Dubbo? Let’s keep looking down.

URL in Dubbo

In general, in Dubbo, the service provider will encapsulate its own relevant information into a URL and register it in zookeeper or other registries, so as to expose its own services. The service consumer will also subscribe the service he wants to call to zookeeper or other registration centers in the form of URL. In Dubbo’s SPI implementation, URL will participate in the logic processing of extension implementation. Therefore, URL is very important in the implementation of Dubbo. It can also be said that the URL in Dubbo is the unified contract of Dubbo.

Let’s take a look at what the URL in Dubbo looks like. By debugging the sample source code of Dubbo’s own provider, we can see that the URL in Dubbo is as follows.

dubbo://192.168.175.1:20880/org.apache.dubbo.demo.DemoService?anyhost=true&application=dubbo-demo-annotation-provider&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&interface=org.apache.dubbo.demo.DemoService&methods=sayHello,sayHelloAsync&pid=15012&release=&side=provider&timestamp=1610857629484

This is also the information for the provider to register with zookeeper or other registries. The description of each part is as follows.

  • Dubbo: using the Dubbo protocol.
  • Host: the IP address of the host is 192.168.175.1.
  • Port: the port number is 20880.
  • Path: the request path here is: org.apache.dubbo . demo.DemoService
  • Parameters: the requested parameter information, here is: anyhost = true & application = Dubbo demo annotation provider & decoded = false & Dubbo = 2.0.2 & dynamic = true & generic = false & interface= org.apache.dubbo . demo.DemoService&methods=sayHello ,sayHelloAsync&pid=15012&release=&side=provider&timestamp=1610857629484。

Since Dubbo registers this information with zookeeper or other registries, how does Dubbo encapsulate the URL internally.

In the Dubbo common module, there is a URL class dedicated to encapsulating URLs, as shown below.

How to realize the unified contract in Dubbo?

In the URL class, let’s look at a core constructor, as shown below.

public URL(String protocol,
           String username,
           String password,
           String host,
           int port,
           String path,
           Map<String, String> parameters,
           Map<String, Map<String, String>> methodParameters) {
    if (StringUtils.isEmpty(username)
        && StringUtils.isNotEmpty(password)) {
        throw new IllegalArgumentException("Invalid url, password without username!");
    }
    this.protocol = protocol;
    this.username = username;
    this.password = password;
    this.host = host;
    this.port = Math.max(port, 0);
    this.address = getAddress(this.host, this.port);

    // trim the beginning "/"
    while (path != null && path.startsWith("/")) {
        path = path.substring(1);
    }
    this.path = path;
    if (parameters == null) {
        parameters = new HashMap<>();
    } else {
        parameters = new HashMap<>(parameters);
    }
    this.parameters = Collections.unmodifiableMap(parameters);
    this.methodParameters = Collections.unmodifiableMap(methodParameters);
}

It can be seen that Dubbo’s core encapsulation of URL is basically consistent with that of URL encapsulation in the Internet.

The Dubbo common module in Dubbo provides tool classes for handling URLs: urlbuilder and urlstrparser. This is shown below.
How to realize the unified contract in Dubbo?

The implementation of these two classes is relatively simple. You can read the source code of Dubbo by yourself.

Next, let’s take a look at how URL implements unified contract in Dubbo?

The practical application of URL in Dubbo

Here, we mainly talk about the practical application of URL in Dubbo from three aspects:

  • The application of URL in SPI.
  • The application of URL in service registration.
  • The application of URL in service discovery.

The application of URL in SPI

Everyone who has a little knowledge of Dubbo knows that Dubbo has a high degree of scalability, which is based on its own SPI. In the SPI implemented by Dubbo, URL plays a very important role.

In the implementation of Dubbo SPI, a typical scenario is the interface method modified by @ adaptive annotation. For example, the getregistry() method in the registryfactory interface of Dubbo registry API module is modified by @ adaptive ({“Protocol”}) annotation. This is shown below.

How to realize the unified contract in Dubbo?

This indicates that the getregistry () method in the registryfactory interface is an adapter method. During the running process, Dubbo will dynamically generate the getregistry () methodRegistryFactory$AdaptiveType. For example, generatedRegistryFactory$AdaptiveThe types are as follows.

public class RegistryFactory$Adaptive
              implements RegistryFactory { 
    public Registry getRegistry(org.apache.dubbo.common.URL arg0) { 
        if (arg0 == null) throw new IllegalArgumentException(""); 
        org.apache.dubbo.common.URL url = arg0; 
        String extName = (url.getProtocol() == null ? "dubbo" :  url.getProtocol()); 
        if (extName == null) 
            throw new IllegalStateException(""); 
        RegistryFactory extension = (RegistryFactory) ExtensionLoader.getExtensionLoader(RegistryFactory.class).getExtension(extName); 
        return extension.getRegistry(arg0); 
    } 
}

This code is relatively easy to understand. The generated registryfactory $adaptive will automatically implement the getregistry() method. In the getregistry() method, the protocol parameter in the URL will be obtained to determine the protocol of the URL. If the obtained protocol is empty, the default Dubbo protocol will be used. With this protocol, specific extension implementation classes can be dynamically loaded through SPI.

We found the registryprotocol class in the Dubbo registry API module of Dubbo, as shown below.

How to realize the unified contract in Dubbo?

Find the getregistry () method and break it, as shown below.

How to realize the unified contract in Dubbo?

Next, debug starts Dubbo’s provider example, as shown below.

How to realize the unified contract in Dubbo?

As you can see, the protocol used at this time is zookeeper. As for the implementation of SPI in Dubbo, we will analyze it in detail later. Today, my friends can have a general understanding.

Application of URL in service registration

In the implementation of service registration in Dubbo, URL also plays a very important role. Here, the registry I use is zookeeper, so we can find the zookeeper registry class in the Dubbo registry zookeeper module, as shown below.

How to realize the unified contract in Dubbo?

Find the doregister () method and break it, as shown below.

How to realize the unified contract in Dubbo?

Debug starts the provider example that comes with Dubbo, as shown below.

How to realize the unified contract in Dubbo?

As you can see, the URL registered in zookeeper contains information such as protocol protocol, host host name, port port number, path request path and parameters.

Application of URL in service discovery

When a consumer of a service in Dubbo starts, he or she will subscribe to the zookeeper registry for the service he or she needs to call. How can he or she subscribe through a URL? We also find the dosubscribe () method in the zookeeperregistry class in the Dubbo registry zookeeper module. Place a breakpoint in the dosubscribe () method, as shown below.

How to realize the unified contract in Dubbo?

Start the consumer example that comes with Dubbo, as shown below.

How to realize the unified contract in Dubbo?

We can see that Dubbo’s consumer will pass the following parameters to zookeeper to subscribe to the service.

consumer://192.168.175.1/org.apache.dubbo.demo.DemoService?application=dubbo-demo-annotation-consumer&category=providers,configurators,routers&dubbo=2.0.2&init=false&interface=org.apache.dubbo.demo.DemoService&methods=sayHello,sayHelloAsync&pid=15184&side=consumer&sticky=false&timestamp=1610860963037

Where the protocol is consumer, which represents the subscription protocol. There are three categories to be classified. Interface represents the interface service to subscribe to org.apache.dubbo . demo.DemoService . Methods refers to the method to subscribe to, here is sayhello, sayhello async.

Another point to note is: in the process of service registration, Dubbo will convert the URL to the zookeeper path and register the information to the zookeeper; in the process of service discovery, Dubbo will convert the URL to the zookeeper path, so as to listen to the changes in the zookeeper directory and subscribe to the relevant services.

In a word, a unified contract is implemented through URL in Dubbo. Have you learned?

Recommended reading

OK, that’s all for today. I’m glacier. If you have any questions, you can leave a message at the bottom. Let’s exchange technology, upgrade and force together~~

Recommended Today

Third party calls wechat payment interface

Step one: preparation 1. Wechat payment interface can only be called if the developer qualification has been authenticated on wechat open platform, so the first thing is to authenticate. It’s very simple, but wechat will charge 300 yuan for audit 2. Set payment directory Login wechat payment merchant platform( pay.weixin.qq . com) — > Product […]