Dubbo introduction

On February 15, 2018, Dubbo, Alibaba’s service governance framework, was voted as an Apache Foundation incubation project.

Apache Dubbo is a high-performance, lightweight, open source Java RPC framework that provides three core capabilities: interface-oriented remote method invocation, intelligent fault tolerance and load balancing, and automatic service registration and discovery.

Dubbo architecture

Dubbo provides three core functions: interface-based remote invocation, fault tolerance and load balancing, and automatic registration and discovery of services. The Dubbo framework is widely used within Alibaba, as well as by Dangdang, Qunar, netease Kaola, Didi and others.

Node Role description

node The role that
Provider The service provider that exposes the service
Consumer Service consumer that invokes the remote service
Registry A registry for service registration and discovery
Monitor A monitoring center that collects statistics on service invocation times and invocation time
Container Service run container

Call Relationship Description

  1. The service container is responsible for starting, loading, and running the service provider.
  2. At startup, service providers register their services with the registry.
  3. At startup, service consumers subscribe to the registry for the services they need.
  4. The registry returns a list of service provider addresses to the consumer, and if there are changes, the registry pushes the change data to the consumer based on the long connection.
  5. The service consumer, from the provider address list, selects one provider to call based on the soft load balancing algorithm. If the call fails, selects another one to call.
  6. Service consumers and providers accumulate calls and call times in memory and regularly send statistics to the monitoring center every minute.

Dubbo Quick Start

Let’s start with a simple example to give you an understanding of Dubbo, and then integrate Dubbo based on Spring Boot and Spring Cloud environments.

Dubbo uses the full Spring configuration mode to transparently access applications without any API intrusion. You only need to load Dubbo’s configuration with Spring.

Rely on

JDK 1.6 above and Maven 3.0 above, using Maven multi-module aggregation project to build API module, Provider module and consumer module.

Polymerization engineering

The project structure is as follows:

  • dubbo-api: Service interface
  • dubbo-provider: Dependent service interfaces, concrete business implementations, service providers
  • dubbo-coonsumerDependencies on service interfaces, remote invocation of services, and service consumers

[Img-v8VafkLD-1626229842283)(DubboRPC communication. Assets /image-20200614114932671.png)]

dependencies

The pom.xml of Dubbo-parent relies on Apache Dubbo.

<dependencies>
    <! -- Apache dubbo dependencies -->
    <dependency>
        <groupId>org.apache.dubbo</groupId>
        <artifactId>dubbo</artifactId>
        <version>2.7.7</version>
    </dependency>
</dependencies>
Copy the code

Pom. XML of dubbo-Provider and Dubbo-Consumer rely on the Dubbo-API service interface.

<dependencies>
    <! -- Dubo-API dependencies -->
    <dependency>
        <groupId>org.example</groupId>
        <artifactId>dubbo-api</artifactId>
        <version>1.0 the SNAPSHOT</version>
    </dependency>
</dependencies>
Copy the code

Defining service Interfaces

Helloservice.java in dubo-API

package org.example.service;

/** * Hello service */
public interface HelloService {

    String sayHello(String name);

}
Copy the code

Defining service providers

Implement the service interface in the Provider module

Write helloServiceImp.java in dubo-provider

package org.example.service.impl;

import org.example.service.HelloService;

/** * Service implementation */
public class HelloServiceImpl implements HelloService {

    public String sayHello(String name) {
        return "hello "+ name; }}Copy the code

Configuring the service Provider

dubbo-provider.xml


      
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
       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">

    <! -- Provider application information for calculating dependencies -->
    <dubbo:application name="hello-world-app"/>

    <! Use multicast broadcast registries to expose service addresses
    <dubbo:registry address=Multicast: / / 224.5.6.7: "1234"/>

    <! Expose service on port 20880 with dubbo
    <dubbo:protocol name="dubbo" port="20880"/>

    <! Declare the service interface to be exposed -->
    <dubbo:service interface="org.example.service.HelloService" ref="helloService"/>

    <! Implement the service as a local bean
    <bean id="helloService" class="org.example.service.impl.HelloServiceImpl"/>

</beans>
Copy the code

Load the Spring configuration to start the service

package org.example;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/** * Publish service */
public class Provider {

    public static void main(String[] args) throws Exception {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:dubbo-provider.xml");
        context.start();
        System.out.println("Service registered successfully!");
        System.in.read(); // Press any key to exit}}Copy the code

Defining service consumers

Reference remote services through Spring configuration

dubbo-consumer.xml


      
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
       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">

    <! -- Consumer application name, used to calculate dependencies, not matching conditions, not the same as provider -->
    <dubbo:application name="consumer-of-helloworld-app"  />

    <! Expose discovery service addresses with multicast broadcast registries -->
    <dubbo:registry address=Multicast: / / 224.5.6.7: "1234" />

    <! Create a remote service proxy and use helloService as a local bean -->
    <dubbo:reference id="helloService" interface="org.example.service.HelloService" />

</beans>
Copy the code

Load the Spring configuration and invoke the remote service

package org.example;

import org.example.service.HelloService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/** * call the remote service */
public class Consumer {
    public static void main(String[] args) throws Exception {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:dubbo-consumer.xml");
        context.start();
        HelloService helloService = (HelloService) context.getBean("helloService"); // Get the remote service proxy
        String result = helloService.sayHello("world"); // Execute the remote method
        System.out.println(result); // Displays the result of the call}}Copy the code

Dubbo Common label

  • dubbo:application: Application name
  • dubbo:registry: Connect to registry information (configure the registry)
  • dubbo:protocol: protocol by which the service provider registers the service
    • Dubbo protocol, default
    • The RMI protocol
    • Hessian protocol
    • The HTTP protocol
    • WebService agreement
    • Thrift agreement
    • The Memcached protocol
    • Redis protocol
    • Rest protocol (RESTful)
    • Grpc agreement
  • dubbo:service: Declares the service interface to expose
  • dubbo:reference: Configure subscribed services (generate remote service proxies)

The registry

We have learned a lot about registries, such as ZooKeeper, Eureka, Consul, Nacos, etc. Registries can effectively manage system services, such as publishing service interfaces, automatically removing invalid services, and automatically recovering services.

Dubbo supports five registries: Multicast, Nacos(recommended), ZooKeeper(recommended), Redis, and Simple. This article focuses on the first two, and more information about registries can be found at: dubbo.apache.org/zh-cn/docs/…

Multicast registry

Multicast registries do not need to start any central node, as long as the broadcast address is the same, they can discover each other.

  1. The provider broadcasts its own address at startup
  2. The consumer broadcasts the subscription request when it starts
  3. When the provider receives a subscription request, unicast its own address to the subscriber, if setunicast=false, broadcast to subscribers
  4. When the consumer receives the provider’s address, it connects to the address for an RPC call.

Multicast is limited by the network structure and is only suitable for small-scale applications or development. Multicast address range: 224.0.0.0 to 239.255.255.255

configuration

<dubbo:registry address=Multicast: / / 224.5.6.7: "1234" />
Copy the code

or

<dubbo:registry protocol="multicast" address="224.5.6.7:1234" />
Copy the code

To reduce the amount of broadcasts, Dubbo default uses unicast provider address information to the consumer. If multiple consumer processes are started on a machine at the same time, the consumer needs to declare unicast=false, otherwise only one consumer will receive the message.

When the server and the consumer run on the same machine, the consumer also needs to declare unicast=false. Otherwise, the consumer cannot receive messages and No Provider available for the Service is abnormal.

<dubbo:registry address="Multicast: / / 224.5.6.7:1234? unicast=false" />
Copy the code

or

<dubbo:registry protocol="multicast" address="224.5.6.7:1234">
    <dubbo:parameter key="unicast" value="false" />
</dubbo:registry>
Copy the code

The ZooKeeper registry

Zookeeper is a subproject of Apache Hadoop. It is a tree directory service that supports change push and is suitable for Dubbo service registries. It has high industrial intensity and can be used in production environments.

Process description:

  • Service provider startup: to/dubbo/com.foo.BarService/providersWrite your OWN URL address in the directory.
  • Service consumer startup: Subscribe/dubbo/com.foo.BarService/providersThe provider URL in the directory. And to the/dubbo/com.foo.BarService/consumersWrite your OWN URL address in the directory.
  • Monitor center startup: Subscribe/dubbo/com.foo.BarServiceAll provider and consumer urls under the directory.

Supports the following functions:

  • The registry can automatically delete provider information when the provider has an abnormal outage such as power outage;
  • When the registry is restarted, the registration data and subscription requests can be automatically restored.
  • When the session expires, the registration data and subscription requests can be automatically restored.
  • When setting<dubbo:registry check="false" />Failed registration and subscription requests are recorded, and the background periodically tries again.
  • through<dubbo:registry username="admin" password="1234" />Set zooKeeper login information.
  • through<dubbo:registry group="dubbo" />If the root node of ZooKeeper is not configured, the default root node is used.
  • support*The wildcard<dubbo:reference group="*" version="*" />Providers for all groupings and versions of subscribeable services.

As The old golden partner of Dubbo, ZooKeeper, we have already shared how to use Dubbo in our separate presentation. This article is a series of Spring Cloud Alibaba articles focusing on Nacos. So ZooKeeper won’t be talked about here.

Nacos Registry

Nacos is an open source tool launched by Alibaba for service discovery and configuration management of distributed systems. Nacos is an important registry implementation in the Dubbo ecosystem.

Preparatory work

Before you integrate Nacos into your Dubbo project, make sure the Nacos service is started in the background.

Quick learning

The steps for Dubbo to merge Nacos into a registry are simple and can be divided into “Adding Maven dependencies” and “configuring the registry.”

Rely on

The core dependencies are dubbo-Registry -nacos and nacos-client.

<! -- https://mvnrepository.com/artifact/org.apache.dubbo/dubbo-registry-nacos -->
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-registry-nacos</artifactId>
    <version>2.7.7</version>
</dependency>
<! -- https://mvnrepository.com/artifact/com.alibaba.nacos/nacos-client -->
<dependency>
    <groupId>com.alibaba.nacos</groupId>
    <artifactId>nacos-client</artifactId>
    <version>1.3.0</version>
</dependency>
Copy the code

Configuring the Registry

The service provider and service consumer need only adjust the Address property configuration.

Single-machine configuration:

<! -- Using the Nacos registry, standalone -->
<dubbo:registry address="Nacos: / / 127.0.0.1:8848"/>
<! - or - >
<dubbo:registry protocol="nacos" address="127.0.0.1:2181"/>
Copy the code

Cluster configuration:

<! -- Using the Nacos registry, Cluster Edition -->
<dubbo:registry address="Nacos: / / 192.168.10.101:2181? Backup = 192.168.10.102:2181192168 10.103:2181"/>
<! - or - >
<dubbo:registry protocol="nacos" address="192.168.10.101:2181192168 10.102:2181192168 10.103:2181"/>
Copy the code

Then, restart your Dubbo application and Dubbo’s service offering and consumption information will be displayed in the Nacos console.

Spring Cloud Alibaba Nacos integration with Dubbo

In previous articles, whether we study Eureka, Consul or Nacos, the Ribbon is responsible for communication between services. Next, we will use Dubbo to replace the Ribbon.

Polymerization engineering

Dubo-demo polymerization project. RELEASE, Spring Cloud hoxton.sr5

The project structure is as follows:

  • service-api: Service interface
  • product-service: goods and services, service providers, provided/product/listinterface
  • order-service: Order service, service consumer, remote call goods service

dependencies

Dubbo – demo of pom. The XML.


      
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <! -- Project coordinate address -->
    <groupId>com.example</groupId>
    <! -- Project module name -->
    <artifactId>dubbo-demo</artifactId>
    <packaging>pom</packaging>
    <! -- Project Version Name SNAPSHOT version, official version RELEASE -->
    <version>1.0 the SNAPSHOT</version>
    <modules>
        <module>service-api</module>
        <module>product-service</module>
        <module>order-service</module>
    </modules>

    <! -- Inherits spring-boot-starter-parent dependency -->
    <! -- Use inheritance mode, implement reuse, conform to inheritance can be used -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0. RELEASE</version>
    </parent>

    <! -- Define the dependency version number centrally, but do not introduce the dependency version number, when the subproject uses the declared dependency, can not add the dependency version number, so that the unified management project uses the dependency version number.
    <properties>
        <! -- Spring Cloud hoxton.sr5 dependencies -->
        <spring-cloud.version>Hoxton.SR5</spring-cloud.version>
        <! -- Spring Cloud Alibaba -->
        <spring-cloud-alibaba.version>2.1.0. RELEASE</spring-cloud-alibaba.version>
    </properties>

    <! Project dependency management The parent project only declares dependencies. The child project needs to specify the required dependencies (omit version information).
    <dependencyManagement>
        <dependencies>
            <! -- Spring Cloud dependencies -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <! -- Spring Cloud Alibaba -->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>
Copy the code

Service – API pom. XML


      
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>dubbo-demo</artifactId>
        <groupId>com.example</groupId>
        <version>1.0 the SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>service-api</artifactId>

    <dependencies>
        <! -- Lombok dependency -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

</project>
Copy the code

Product-service requires Nacos, Dubbo and service-API dependencies. The complete dependencies are as follows:


      
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <! -- Inheriting parent dependencies -->
    <parent>
        <artifactId>dubbo-demo</artifactId>
        <groupId>com.example</groupId>
        <version>1.0 the SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>product-service</artifactId>

    <! -- Project dependencies -->
    <dependencies>
        <! -- Spring Cloud Alibaba NacOS Discovery
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <! -- Spring Cloud Alibaba dubbo -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dubbo</artifactId>
        </dependency>
        <! Spring Boot Web dependency -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <! -- service-api dependencies -->
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>service-api</artifactId>
            <version>1.0 the SNAPSHOT</version>
        </dependency>

        <! -- Spring Boot test dependency -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

</project>
Copy the code

Order-service requires Nacos and Dubbo dependencies as well as service-API dependencies.


      
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <! -- Inheriting parent dependencies -->
    <parent>
        <artifactId>dubbo-demo</artifactId>
        <groupId>com.example</groupId>
        <version>1.0 the SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>order-service</artifactId>

    <! -- Project dependencies -->
    <dependencies>
        <! -- Spring Cloud Alibaba NacOS Discovery
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <! -- Spring Cloud Alibaba dubbo -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dubbo</artifactId>
        </dependency>
        <! Spring Boot Web dependency -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <! -- service-api dependencies -->
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>service-api</artifactId>
            <version>1.0 the SNAPSHOT</version>
        </dependency>

        <! -- Spring Boot test dependency -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

</project>
Copy the code

Defining service Interfaces

We define the entity class and service interface information in the service-API module.

Entity class

package com.example.product.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product implements Serializable {

    private Integer id;
    private String productName;
    private Integer productNum;
    private Double productPrice;

}
Copy the code
package com.example.product.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Order implements Serializable {

    private Integer id;
    private String orderNo;
    private String orderAddress;
    private Double totalPrice;
    private List<Product> productList;

}
Copy the code

The service interface

package com.example.product.service;

import com.example.product.pojo.Product;

import java.util.List;

/** ** ** /
public interface ProductService {

    /** ** query the product list **@return* /
    List<Product> selectProductList(a);

}
Copy the code

Defining service providers

The configuration file

The configuration file needs to be configured with Nacos registry and Dubbo information. The core configuration is as follows:

server:
  port: 7070 # port

spring:
  application:
    name: product-service # app name
  Configure the Nacos registry
  cloud:
    nacos:
      discovery:
        enabled: true If you don't want to use Nacos for service registration and discovery, set it to false
        server-addr: 127.0. 01.: 8848 # Nacos server address, standalone version

# Dubbo
dubbo:
  Provider application information used to calculate dependencies
  application:
    name: product-service
  Expose the service address using the NACOS registry
  registry:
    protocol: nacos
    address: spring-cloud://localhost
  Expose service on port 20880 with dubbo protocol
  protocol:
    name: dubbo
    port: 20880
  # Scan for exposed services, which can be annotated @enabledubbo instead
  #scan:
  # base-packages: com.example.service
Copy the code

Service provider

The product – service ProductServiceImpl. Java

package com.example.service.impl;

import com.example.product.pojo.Product;
import com.example.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;

import java.util.Arrays;
import java.util.List;

/** ** Commodity service * timeout Timeout period for invoking the service * version indicates the version number * Group indicates the group * Interface, group, and version specify a service */
@Slf4j
@service (timeout = 5000, version = "1.0", group = "product-service")
public class ProductServiceImpl implements ProductService {

    /** ** query the product list **@return* /
    @Override
    public List<Product> selectProductList(a) {
        log.info("Commodity service query commodity information...");
        return Arrays.asList(
                new Product(1.Huawei Mobile.1.5800D),
                new Product(2."Lenovo Notebook".1.6888D),
                new Product(3."Xiaomi Tablet".5.2020D)); }}Copy the code

Note that the @service annotation is not a Spring annotation but a Dubbo annotation:

Start the class

The startup class scans for services to be exposed via the @enabledubbo annotation, which can be omitted if configured in the configuration file.

package com.example;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

// Scan for exposed services
@EnableDubbo(scanBasePackages = "com.example.service")
// Enable the @enableDiscoveryClient annotation. This annotation is enabled by default in the current version
//@EnableDiscoveryClient
@SpringBootApplication
public class ProductServiceApplication {

    public static void main(String[] args) { SpringApplication.run(ProductServiceApplication.class, args); }}Copy the code

Defining service consumers

The configuration file

The configuration file needs to be configured with Nacos registry and Dubbo information. The core configuration is as follows:

server:
  port: 9090 # port

spring:
  application:
    name: order-service # app name
  Configure the Nacos registry
  cloud:
    nacos:
      discovery:
        enabled: true If you don't want to use Nacos for service registration and discovery, set it to false
        server-addr: 127.0. 01.: 8848 # Nacos server address, standalone version

# Dubbo
dubbo:
  # consumer application name, used to calculate dependencies, not matching conditions, not the same as provider
  application:
    name: order-service
  Discover services exposed in the NACOS registry
  registry:
    protocol: nacos
    address: spring-cloud://localhost
  cloud:
    subscribed-services: product-service Subscribe service, the name of the service to be called remotely
Copy the code

Service consumer

The order – service OrderServiceImpl. Java

package com.example.service.impl;

import com.example.product.pojo.Order;
import com.example.product.service.ProductService;
import com.example.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    // Dubbo provides the @Reference annotation to replace the @autowired annotation for introducing remote services
    If the version and group information are set when registering the service, the version and group information must be set when invoking the remote service
    @reference (timeout = 5000, version = "1.0", group = "product-service")
    private ProductService productService;

    /** * select order ** from primary key@param id
     * @return* /
    @Override
    public Order selectOrderById(Integer id) {
        log.info("Order service query order information...");
        return new Order(id, "order-001"."China".22788D, productService.selectProductList()); }}Copy the code

Start the class

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

// Enable the @enableDiscoveryClient annotation. This annotation is enabled by default in the current version
//@EnableDiscoveryClient
@SpringBootApplication
public class OrderServiceApplication {

    public static void main(String[] args) { SpringApplication.run(OrderServiceApplication.class, args); }}Copy the code

test

Start Nacos server first and then start the service provider product – service, visit: http://localhost:8848/nacos/ the console display as follows:

Then start the service consumer and the console displays the following:

The order service invokes the remote goods service with the following result:

Dubbo load balancing

For cluster load balancing, Dubbo provides multiple load balancing policies. The default value is Random. You can also expand the load balancing policies.

Load Balancing Policy

Random LoadBalance

  • Random, set random probability according to weight.
  • The probability of collision on a section is high, but the distribution is more uniform with the increase of adjustment dosage, and the distribution is more uniform after using weight according to the probability, which is conducive to dynamic adjustment of provider weight.

RoundRobin LoadBalance

  • Polling, the polling ratio is set according to the weight after the convention.
  • There is the problem of slow providers accumulating requests, for example: the second machine is slow but not hung up, gets stuck when the request is switched to the second machine, and over time all the requests get stuck to the second machine.

LeastActive LoadBalance

  • Minimum number of active calls, ping value (low latency) calls, same latency case random.
  • Make slower providers receive fewer requests, because slower providers have a larger difference in the count before and after the invocation.

ConsistentHash LoadBalance

  • Consistent Hash, where requests with the same parameters are always sent to the same provider.
  • When a provider hangs, requests originally sent to that provider are spread over other providers based on virtual nodes without drastic changes.
  • Algorithm is used to refer to: en.wikipedia.org/wiki/Consis…
  • By default, only the first parameter Hash is used. If you want to change it, configure it"Dubbo: parameter key =" hash. The arguments "value =" 0, 1 "/ >
  • By default, 160 virtual nodes are used. If you want to change the number, configure the number<dubbo:parameter key="hash.nodes" value="320" />

configuration

Weights are not typically assigned at the code level in a project, but are assigned to service dynamics through the monitoring center (Dubo-admin),

xml

Service level of the server

<dubbo:service interface="..." loadbalance="roundrobin" weight="100" />
Copy the code

Client service level

<dubbo:reference interface="..." loadbalance="roundrobin" />
Copy the code

Server method level

<dubbo:service interface="..." weight="100">
    <dubbo:method name="..." loadbalance="roundrobin"/>
</dubbo:service>
Copy the code

Client method level

<dubbo:reference interface="...">
    <dubbo:method name="..." loadbalance="roundrobin"/>
</dubbo:reference>
Copy the code

yaml

dubbo:
  provider:
    loadbalance: roundrobin
    weight: 100
  consumer:
    loadbalance: roundrobin
Copy the code

annotations

@Service(loadbalance = "roundrobin", weight = 100)
@Reference(loadbalance = "roundrobin")
Copy the code

At this point, all the knowledge of Dubbo RPC communication is explained.

stent_hashing

  • By default, only the first parameter Hash is used. If you want to change it, configure it"Dubbo: parameter key =" hash. The arguments "value =" 0, 1 "/ >
  • By default, 160 virtual nodes are used. If you want to change the number, configure the number<dubbo:parameter key="hash.nodes" value="320" />

configuration

Weights are typically not specified at the code level in a project, but are dynamically assigned to services through a monitoring center (Dubbo-admin)

xml

Service level of the server

<dubbo:service interface="..." loadbalance="roundrobin" weight="100" />
Copy the code

Client service level

<dubbo:reference interface="..." loadbalance="roundrobin" />
Copy the code

Server method level

<dubbo:service interface="..." weight="100">
    <dubbo:method name="..." loadbalance="roundrobin"/>
</dubbo:service>
Copy the code

Client method level

<dubbo:reference interface="...">
    <dubbo:method name="..." loadbalance="roundrobin"/>
</dubbo:reference>
Copy the code

yaml

dubbo:
  provider:
    loadbalance: roundrobin
    weight: 100
  consumer:
    loadbalance: roundrobin
Copy the code

annotations

@Service(loadbalance = "roundrobin", weight = 100)
@Reference(loadbalance = "roundrobin")
Copy the code

At this point, all the knowledge of Dubbo RPC communication is explained.