preface

Hello everyone, today we start to share – Dubbo special Dubbo Delay Service exposure. In the previous section, we introduced Dubbo stubs and Mocks. We illustrated common usage scenarios and analyzed source code to analyze their implementation principles. At the same time, we learned that Dubbo stubs and Mocks are implemented based on wrappings of calling proxy objects. This will allow us to do some pre – and post-processing when we invoke the service. Some friend may encounter such a scenario: there are many in our application service of the local cache or distributed cache, the cache may need to load for a period of time so we hope that in this cache loading process interfaces do not provide services, it have a mechanism to let us to cache after completion of loading again exposed service mechanism? In this chapter we address this problem by introducing the Dubbo delayed exposure service. So what is delayed service exposure? And what is the implementation principle of delayed service exposure? Let’s get started quickly!

1. Introduction to delayed service exposure

In the current version of Dubbo2.7.x we are using, the time to expose the service is when the Spring container has started and broadcasts the ApplicationContextEvent event. Delay exposure is when the ApplicationContextEvent event is received and a delay of a specified amount of time is started before the service is exposed. The core of delayed service exposure is a delay scheduler that starts service exposure when the delay time is up. The configuration parameter is delay=”5000″, where the time unit is milliseconds.

** Other Dubbo versions of the service exposure may have some discrepancies, readers are based on the latest version.

2. Usage

The latency service exposure can be configured as XML or annotations and the delay time is specified in milliseconds.

2.1 XML Configuration Mode

    <! -- Delay 1 second to expose Dubbo service -->
    <dubbo:service interface="com.muke.dubbocourse.protocol.api.BookFacade" ref="bookFacade" delay="1000" />
Copy the code

If delay=”-1″ is set to expose the service after the Spring container is initialized.

2.2 Comments Configuration Mode

@DubboService(delay = 1000)
public class BookFacadeImpl implements BookFacade {}Copy the code

Use the @dubboService annotation or @service annotation. Delay = 1000 Indicates that the service is exposed after 1 second.

3. Application scenarios

From the introduction of delayed service exposure above, we can know that delayed service exposure is actually to configure a fixed delay time for the service to be exposed. Once the delay time reaches, the service will be exposed immediately. Based on the timeliness of the above service exposure, we briefly introduce some scenarios commonly used in work:

  1. Cache warm-up: When our exposed service relies on static data that is loaded into a database or file and cached into application memory. At this point we can preload the cache during the time period of service latency exposure.

  2. Dependent resources: Suppose the service we provide externally needs to depend on another service, and the exposure time of the other service is slow. Then we can delay the exposure of the currently exposed service to reduce the timeout exceptions when calling the dependent service.

4. Example demonstration

Let’s also use the example of getting a list of books. The project structure is as follows:

Since delayed service exposure is the configuration of the service provider, we will only look at the service provider’s XML configuration dubo-provider-xml.xml:


      
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">

    <dubbo:application name="demo-provider" metadata-type="remote"/>

   <! -- Registry -->
    <dubbo:registry address=Zookeeper: / / "127.0.0.1:2181"/>

    <bean id="bookFacade" class="com.muke.dubbocourse.delayexport.provider.BookFacadeImpl"/>

    <! -- Delay 1 second to expose Dubbo service -->
    <dubbo:service interface="com.muke.dubbocourse.common.api.BookFacade" ref="bookFacade" delay="1000"/>

</beans>

Copy the code

In the XML configuration above, delay=”1000″ means that the service will be exposed after 1 second after the Spring container is started. The annotation configuration is similar and will not be demonstrated.

5. Implementation principle

Let’s simply analyze the source code exposed by the service. We all know that the ApplicationContextEvent event is emitted when the Spring container is started, We can see the org. Apache. Dubbo. Config. Spring. Context. DubboBootstrapApplicationListener# onApplicationContextEvent method core code:

    public void onApplicationContextEvent(ApplicationContextEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            // The Spring container is started
            onContextRefreshedEvent((ContextRefreshedEvent) event);
        } else if (event instanceof ContextClosedEvent) {
            // The Spring container is closedonContextClosedEvent((ContextClosedEvent) event); }}Copy the code

When receiving the ContextRefreshedEvent incident will eventually call org. Apache. Dubbo. Config. The bootstrap. DubboBootstrap# start method to start the service registry key code is as follows:

    public DubboBootstrap start(a) {
         // Check whether the service is started to prevent repeated exposure of the service note: here is the atomic operation
        if (started.compareAndSet(false.true)) {
            initialize();
            / /..
            // Expose the Dubbo service
            exportServices();

            / /...
        }
        return this;
    }
Copy the code

The code above does an atomic operation to set the startup flag to prevent repeated exposure of the service. Its exportServices code is as follows:

    /*** ** Dubbo service export **@author liyong
     * @dateShew forth the 2020-03-01 *@param
     * @exception
     * @return void
     **/
    private void exportServices(a) {
        // Loop through all configurations that require service exposure
        configManager.getServices().forEach(sc -> {
            // TODO, compatible with ServiceConfig.export()
            ServiceConfig serviceConfig = (ServiceConfig) sc;
            serviceConfig.setBootstrap(this);

            // Whether to export it asynchronously
            if (exportAsync) {
                // Get the thread poolExecutorService executor = executorRepository.getServiceExporterExecutor(); Future<? > future = executor.submit(() -> {// Asynchronous service exposure
                    sc.export();
                });
                asyncExportingFutures.add(future);
            } else {
                // The synchronization service exposes the exportsc.export(); exportedServices.add(sc); }}); }Copy the code

The above code loops through all Dubbo services, noting that there is an exportAsync flag to determine whether the service is exposed asynchronously (which means that execution on another thread does not block the current thread). We see the main service exposed code below org. Apache. Dubbo. Config. ServiceConfig# export methods:

 /** ** service exposed **@author liyong 
     * @date 10:55 PM 2020/11/18 
     * @param  
     * @exception 
     * @return void 
     **/
    public synchronized void export(a) {

       / /...

        // Whether to delay exposure judgment
        if (shouldDelay()) {
            // Delay exposure
            DELAY_EXPORT_EXECUTOR.schedule(this::doExport, getDelay(), TimeUnit.MILLISECONDS);
        } else {
            // Service exposuredoExport(); }}Copy the code

Delay_export_executor.schedule (this::doExport, getDelay(), timeUnit.milliseconds) uses the delay scheduler to expose services.

6. Summary

In this section, we mainly study the delayed service exposure in Dubbo and how to use it, and also analyze the principle of the implementation of delayed service exposure, which is essentially to expose the service through the delay scheduler, of which the delay scheduler is the key.

The highlights of this lesson are as follows:

  1. Understand Dubbo delay service exposure

  2. You learned how to use delayed service exposure

  3. Learn about delayed service exposure usage scenarios

  4. Understand how delayed service exposure is implemented

The author

Personally engaged in the financial industry, I have worked in chongqing’s first-class technical team of Yiji Pay, Sijian Technology and an online car hailing platform, and now I am working in a bank responsible for the construction of unified payment system. I have a strong interest in the financial industry. It also practices big data, data storage, automated integration and deployment, distributed microservices, responsive programming, and artificial intelligence. At the same time, he is also keen on technology sharing, creating public accounts and blog sites to share knowledge system. Concern public number: young IT male get latest technical article push!

Blog: Youngitman.tech

Wechat Official Account: