Apache Dubbo: Take you to the world of dubbo

Apache Dubbo: Take you to the world of dubbo

premise

This blog is written with reference to dubbo official documents and the video of Mr. Lei Fengyang from Shang Silicon Valley. If there are any deficiencies, please leave your footprints and I will correct them in time. Also, in the later learning process, if the development tool you use is IDEA, please set it to Allow parallel Run mode, which will run multiple processes to simulate multiple consumers and providers. The specific steps are as follows:
Step 1: Select Edit Configurations to enter option editing
insert image description here
Step 2: Check Allow parallel Run
insert image description here
Finally: The effect is as follows
insert image description here
After these preparations are done, let's start the dubbo learning journey.

8.1 Evolution of website applications

With the development of the Internet, the scale of website applications continues to expand, and the conventional vertical application architecture can no longer cope. Distributed service architecture and mobile computing architecture are imperative, and a governance system is urgently needed to ensure the orderly evolution of the architecture .
[External link image transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the image and upload it directly (img-AjkLC1nE-1628218469838)(../Typora/Typora-images/image-20210730192500590.png)]

8.1.1 Single Application Architecture

When the website traffic is small, only one application is needed to deploy all functions together to reduce deployment nodes and costs. At this time, the data access framework (ORM) used to simplify the workload of adding, deleting, modifying and checking is the key.
[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-gOK6ZEbw-1628218469845)(../Typora/Typora-images/image-20210801095129855.png)]

8.1.2 Vertical Application Architecture

When the number of visits gradually increases, the acceleration brought by adding machines to a single application becomes smaller and smaller. One of the ways to improve efficiency is to split the application into several independent applications to improve efficiency. At this time, the web framework (MVC) used to accelerate the development of front-end pages is the key.
[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-0khHXUo7-1628218469851)(../Typora/Typora-images/image-20210801095232797.png)]

8.1.3 Distributed service architecture

A distributed system is a collection of independent computers that appears to users as a single related system.

When there are more and more vertical applications, the interaction between applications is inevitable. The core business is extracted as an independent service, and a stable service center is gradually formed, so that front-end applications can respond to changing market demands more quickly. At this time, the distributed service framework (RPC) for improving business reuse and integration is the key.
[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-v5GJdDnS-1628218469854)(../Typora/Typora-images/image-20210801095320941.png)]

8.1.4 Mobile Computing Architecture

When there are more and more services, problems such as capacity evaluation and waste of small service resources gradually appear. At this time, it is necessary to add a scheduling center to manage the cluster capacity in real time based on access pressure and improve cluster utilization. At this time, the resource scheduling and management center (SOA) for improving machine utilization is the key.
[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-cgtc4lqG-1628218469856)(../Typora/Typora-images/image-20210801095423904.png)]

8.2 RPC

RPC is Remote Procedure Call (Remote Procedure Call), which is a method of interprocess communication, which allows a program to call a procedure or function in another address space (usually another machine sharing a network). RPC has two core modules: communication and serialization.

Serialization: data transfer requires conversion

8.3 Dubbo

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-0vW81Ye3-1628218469857)(../Typora/Typora-images/image-20210804233549298.png)]
Apache Dubbo (incubating) |ˈdʌbəʊ| is a high-performance, lightweight open source Java RPC framework, which provides three core capabilities: interface-oriented remote method invocation, intelligent fault tolerance and load balancing, and automatic service registration and discovery . In addition, Dubbo adopts the full Spring configuration method to transparently access the application, without any API intrusion into the application, just load the Dubbo configuration with Spring.

Summary: Apache Dubbo is a microservice development framework, which provides two key capabilities of RPC communication and microservice governance. (dubbo3)

8.3.1 Dubbo architecture

Dubbo2's service discovery model: Provider registers the service address, Consumer coordinates and discovers the service address through the registration center, and then initiates communication with the address. This is the classic service discovery process used by most microservice frameworks.
[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-pbgfJfQc-1628218469858)(../Typora/Typora-images/image-20210730202720503.png)]

node role description effect
Provider service provider exposed service
Consumer service consumer call remote service
Registry registration center Service registration and discovery; Zookeeper is recommended
Monitor monitoring Center Statistics service call times and call time
Container container service running

Description of calling relationship

1. The service container is responsible for starting, loading, and running the service provider.

2. When the service provider starts, it registers the services it provides with the registration center.

3. When the service consumer starts, it subscribes to the registration center for the services it needs.

4. The registration center returns the service provider address list to the consumer. If there is a change, the registration center will push the change data to the consumer based on the long connection.

5. The service consumer, from the provider address list, selects a provider to call based on the soft load balancing algorithm, and if the call fails, select another provider to call.

6. Service consumers and providers accumulate the number of calls and call time in memory, and regularly send statistical data to the monitoring center every minute.

8.3.2 RPC communication protocol

Dubbo3 provides Triple (Dubbo3) and Dubbo2 protocols, which are native protocols of the Dubbo framework.

The protocol is the core of RPC, which regulates the content and format of data transmission in the network.

8.3.3 dubbo configuration

Reference document: https://dubbo.apache.org/zh/docs/references/configuration/overview/

This article mainly introduces the Dubbo configuration overview, including configuration components, configuration sources, configuration methods and configuration loading process.

configuration components

There are many configuration items in the Dubbo framework. In order to better manage various configurations, they are divided into different components according to their purposes. Finally, all configuration items will be gathered in the URL and passed to the subsequent processing module.

Commonly used configuration components are as follows:

  • application: Dubbo application configuration
  • registry: registration center
  • protocol: service provider RPC protocol
  • service: service provider configuration
  • reference: remote service reference configuration
  • provider: the default configuration or group configuration of the service
  • consumer: default configuration or group configuration of reference
  • monitor: monitor configuration

The relationship between consumer and reference:

The reference can specify a specific consumer. If no consumer is specified, the global default consumer configuration will be used automatically.

The relationship between provider and service:

The service can specify a specific provider, if not specified, it will automatically use the global default provider configuration.

configuration source

Starting from the configuration sources supported by Dubbo, there are 6 configuration sources by default:

  • JVM System Properties, JVM -D parameter
  • System environment, the environment variable of the JVM process
  • Externalized Configuration, externalized configuration, read from the configuration center
  • Application Configuration, the attribute configuration of the application, extracts the attribute set starting with "dubbo" from the Environment of the Spring application
  • The configuration collected by programming interfaces such as API/XML/annotation can be understood as a kind of configuration source, which is a configuration collection method directly oriented to user programming
  • Read configuration file dubbo.properties from classpath

coverage relationship

The following figure shows the priority of the configuration coverage relationship, and the priority decreases from top to bottom:
[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-eNroZGPX-1628218469859)(../Typora/Typora-images/image-20210805190111633.png)]

configuration method

According to the driving mode, it can be divided into the following four modes:

  • API configuration

Assemble configuration through API coding, start Dubbo, publish and subscribe services, API attributes correspond to XML configuration items one by one, for example: ApplicationConfig.setName(“xxx”) corresponds to <dubbo:application name="xxx" />.

Service provider: expose the service interface through ServiceConfig, and publish the service interface to the registration center.

Service consumer: reference the remote service through ReferenceConfig, and subscribe to the service interface from the registry.

Learning documentation: https://dubbo.apache.org/zh/docs/references/configuration/api/

  • XML configuration

Configure various components in XML and support seamless integration with Spring.

Label use explain
<dubbo:service/> service configuration It is used to expose a service and define the meta information of the service. A service can be exposed by multiple protocols, and a service can also be registered to multiple registries
<dubbo:reference/> reference configuration Used to create a remote service proxy, a reference can point to multiple registries
<dubbo:protocol/> protocol configuration Used to configure the protocol information for providing services, the protocol is specified by the provider, and the consumer accepts it passively
<dubbo:application/> application configuration Used to configure current application information, regardless of whether the application is a provider or a consumer
<dubbo:registry/> Registry configuration Used to configure information related to the connection registry
<dubbo:monitor/> Monitoring Center Configuration It is used to configure related information about connecting to the monitoring center, optional
<dubbo:provider/> provider configuration When a property of ProtocolConfig and ServiceConfig is not configured, this default value is used, optional
<dubbo:consumer/> consumer configuration When a property of ReferenceConfig is not configured, this default value is used, optional

provider.xml example

<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.xsd
       http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
    <dubbo:application name="demo-provider"/>
    <dubbo:registry address="zookeeper://127.0.0.1:2181"/>
    <dubbo:protocol name="dubbo" port="20890"/>
    <bean id="demoService" class="org.apache.dubbo.samples.basic.impl.DemoServiceImpl"/>
    <dubbo:service interface="org.apache.dubbo.samples.basic.api.DemoService" ref="demoService"/>
</beans>

consumer.xml example

<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.xsd
       http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
    <dubbo:application name="demo-consumer"/>
    <dubbo:registry group="aaa" address="zookeeper://127.0.0.1:2181"/>
    <dubbo:reference id="demoService" check="false" interface="org.apache.dubbo.samples.basic.api.DemoService"/>
</beans>

Coverage relationship for different granularity configurations

(1) Method level takes precedence, interface level takes second place, and global configuration takes second place.

(2) If the levels are the same, the consumer takes precedence, followed by the provider.

Learning documents: https://dubbo.apache.org/zh/docs/references/configuration/xml/

  • Annotation placement

Expose services and reference service interfaces in the form of annotations, support seamless integration with Spring, and require 2.6.3version support and above.

@Service annotation exposes service + @Reference reference service + application.properties (configure dubbo)

Reference document: https://dubbo.apache.org/zh/docs/references/configuration/annotation/

  • attribute configuration

Generate configuration components according to the attribute Key-value, similar to SpringBoot’s ConfigurationProperties, currently all configurations supported by Dubbo are .propertiesformatted, and attribute configurations can also be placed in Spring applications application.yml, and the tree hierarchy is more readable. .

Attribute and XML configuration mapping rules: you can combine the xml tag name and attribute name, separated by '.', one attribute per line.

dubbo.application.name=foo 相当于 <dubbo:application name=“foo” />

Reference document: https://dubbo.apache.org/zh/docs/references/configuration/properties/


.

8.3.4 install zookeeper

registration center

1. Download the zookeeper URL https://archive.apache.org/dist/zookeeper/zookeeper-3.5./

2. Decompress zookeeper, decompress and run zkServer.cmd, the first run will report an error, there is no zoo.cfg configuration file

3. Modify the zoo.cfg configuration file. Copy a copy of zoo_sample.cfg under conf and rename it to zoo.cfg.

Note several important positions:

dataDir=./ Directory for temporary data storage (writable relative path)

clientPort=2181 Zookeeper restarts zookeeper after the port number modification is completed

4. Use zkCli.cmd to test

ls /: List all nodes saved under the zookeeper root

create –e /atguigu 123: Create an atguigu node with a value of 123

get /atguigu: Get the value of the /atguigu node


8.3.5 Install dubbo-admin

monitoring Center

dubbo itself is not a service software. It is actually a jar package that can help your java program connect to zookeeper, and use zookeeper to consume and provide services . So you don't need to start any dubbo service on Linux.

But in order to allow users to better manage and monitor many dubbo services, the official provides a visual monitoring program, but this monitoring will not affect the use even if it is not installed.

1. Download dubbo-admin

https://github.com/apache/incubator-dubbo-ops

2. Enter the directory and modify the dubbo-admin configuration

Modify src\main\resources\application.properties to specify the address of zookeeper (the default port of zookeeper is 2181)

server.port=7001
spring.velocity.cache=false
spring.velocity.charset=UTF-8
spring.velocity.layout-url=/templates/default.vm
spring.messages.fallback-to-system-locale=false
spring.messages.basename=i18n/message
spring.root.password=root
spring.guest.password=guest

dubbo.registry.address=zookeeper://127.0.0.1:2181

3. Package dubbo-admin

 mvn clean package 

4. Run dubbo-admin

java -jar dubbo-admin-0.0.1-SNAPSHOT.jar

Login with root/root by default
[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-8C8ihz0v-1628218502753)(../Typora/Typora-images/image-20210801110445059.png)]
Note: The premise is to make zookeeper start first

8.3.6 Install dubbo-monitor-simple

optional, simplemonitoring Center

Install

1. Download dubbo-ops

https://github.com/apache/incubator-dubbo-ops

2. Modify the configuration to specify the registration center address (optional)

Enter dubbo-monitor-simple\src\main\resources\conf to modify the dubbo.properties file
[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-PDXf4JR1-1628218502763)(../Typora/Typora-images/image-20210804095626540.png)]

3. Package dubbo-monitor-simple

mvn clean package

4. Unzip the tar.gz file and run start.bat
5. Start accessing 8080

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-hp4oXsJY-1628218502765)(../Typora/Typora-images/image-20210804095857468.png)]

Monitoring Center Configuration

     所有服务配置连接监控中心,进行监控统计
    <!-- 监控中心协议,如果为protocol="registry",表示从注册中心发现监控中心地址,否则直连监控中心 -->
	<dubbo:monitor protocol="registry"></dubbo:monitor>

The downtime of Simple Monitor will not affect the call between Consumer and Provider, so there is no risk in using it in a production environment.


8.3.7 dubbo entry case

Requirements: The order service web module is on server A, the user service module is on server B, and A can remotely call B's functions.

Engineering structure:

  • Subcontract

    It is recommended to put the service interface, service model, service exception, etc. in the API package.

  • granularity

    The service interface should be as granular as possible, and each service method should represent a function.
    [External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-9NLqbu3e-1628218502769)(../Typora/Typora-images/image-20210801112454044.png)]

create module

  • gmall-interface (public interface layer) model, service, exception...

    Role: define the public interface, and can also import the public dependent
    [External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-Go6V2BVZ-1628218502771)(../Typora/Typora-images/image-20210804163014594.png)]
    Entity entity class

    @Data
    @ToString
    @NoArgsConstructor
    @AllArgsConstructor
    public class User implements Serializable {
          
          
        private Integer id;
        private String name;
        private String userAddress;
        private String userId;
        private String phoneNum;
    }
    

    service interface

    /*UserService.java
    */
    public List<User> getUserAddressList(String userId);
    
    /*
    OrderService.java
    */
    public List<User> initOrder(String userId);
    
  • gmall-user user module (implementation of user interface)

    Import the public interface through pom.xml

    <dependency>
    			<groupId>com.pinkhub</groupId>
    			<artifactId>gmall-api</artifactId>
    			<version>0.0.1-SNAPSHOT</version>
    </dependency>
    

    Write the user interface implementation class

    public class UserServiceImpl implements UserService {
          
          		
    	@Override
    	public List<User> getUserAddressList() {
          
          
    		User user1 = new User(1, "屈明明", "河南省洛阳市洛龙区", "212", "13137041655");
            User user2 = new User(2, "屈明明", "陕西省渭南市白水县", "212", "13759699712");
            List<User> users = Arrays.asList(user1, user2);
            return users;
    	}
    }
    
  • gmall-order-web order module (call user module)

    Import the public interface through pom.xml

    <dependency>
    			<groupId>com.pinkhub</groupId>
    			<artifactId>gmall-api</artifactId>
    			<version>0.0.1-SNAPSHOT</version>
    </dependency>
    

Use dubbo to transform

Document reference: https://dubbo.apache.org/zh/docsv2.7/user/quick-start/

xml-based configuration mode

  • Transform gmall-user asservice provider

    • introduce dubbo

      Since we use zookeeper as the registration center, we need to operate zookeeper
      (1) Dubbo version 2.6 before introduces zkclient to operate zookeeper
      (2) Dubbo 2.6 and later versions introduce curator to operate zookeeper

      <!-- 引入dubbo -->
      <dependency>
      	<groupId>com.alibaba</groupId>
      	<artifactId>dubbo</artifactId>
      	<version>2.6.2</version>
      </dependency>
      <dependency>
      	<groupId>org.apache.curator</groupId>
      	<artifactId>curator-framework</artifactId>
      	<version>2.12.0</version>
      </dependency>
      
    • configuration provider

      provider.xml: declared with Spring configurationexposed service

      <?xml version="1.0" encoding="UTF-8"?>
      <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"
             xmlns:context="http://www.springframework.org/schema/context"
             xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd
      		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
      		http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd
      		http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
          <!--1.指定当前应用/服务的名字-->
          <dubbo:application name="gmall-user"></dubbo:application>
          <!--2.指定注册中心的地址  -->
          <dubbo:registry address="zookeeper://127.0.0.1:2181" />
          <!--3.指定通信规则及端口,dubbo协议,将服务暴露在20880端口  -->
          <dubbo:protocol name="dubbo" port="20880" />
          <!--4.暴露服务,ref:指向服务的真正实现对象 -->
          <dubbo:service interface="com.pinkhub.gmallapi.service.UserService" ref="userServiceImpl" />
          <!--5.服务的实现 -->
          <bean id="userServiceImpl" class="com.pinkhub.userserviceprovider.service.impl.UserServiceImpl"></bean>
      </beans>
      
    • Start the Zookeeper registration center and dubbo monitoring center, write test classes, and register the provider to the Zookeeper registration center.

      public static void main(String[] args) throws IOException {
              
              
      		ClassPathXmlApplicationContext ioc = 
      				new ClassPathXmlApplicationContext("classpath:provider.xml");
      		ioc.start();
      		System.in.read();// 按任意键退出 
      	}
      
    • run screenshot
      [External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-J6Hs4qnw-1628218502773)(../Typora/Typora-images/image-20210804154440641.png)]

  • Transform gmall-order-web as a serviceconsumer

    • introduce dubbo

      <!-- 引入dubbo -->
      <dependency>
      	<groupId>com.alibaba</groupId>
      	<artifactId>dubbo</artifactId>
      	<version>2.6.2</version>
      </dependency>
      <dependency>
      	<groupId>org.apache.curator</groupId>
      	<artifactId>curator-framework</artifactId>
      	<version>2.12.0</version>
      </dependency>
      
    • Configure consumer information ----- refer to remote services through Spring configuration

      consumer.xml

      <?xml version="1.0" encoding="UTF-8"?>
      <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" xmlns:context="http://www.springframework.org/schema/context"
             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 http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
          <context:component-scan base-package="com.pinkhub.orderserviceconsumer.service.impl"></context:component-scan>
          <!--1.应用名 -->
          <dubbo:application name="order-service-consumer"></dubbo:application>
          <!-- 2.指定注册中心地址 -->
          <dubbo:registry address="zookeeper://127.0.0.1:2181" />
          <!-- 3.需要调用的远程服务接口,生成远程服务代理-->
          <dubbo:reference id="userService" interface="com.pinkhub.gmallapi.service.UserService"></dubbo:reference>
          <!--4.配置当前消费者的统一规则
                服务启动时不检查,调用时检查;
                配置超时,单位ms;
                重试次数,3次,幂等操作(查、删、修---每次运行结果相同)
          (建议配置)-->
          <dubbo:consumer check="false" timeout="5000" retries="3"/>
      </beans>
      
    • Write OrderServiceImpl.java

      @Service
      public class OrderServiceImpl implements OrderService{
              
              
          @Autowried
          UserService userService;
          public void initOrder(){
              
              
              //1.查询用户的收货地址
              List<UserAddress> addressList=userService.getUserAddressList();
              for(UserAddress userAddress:addressList){
              
              
                  System.out.println(addressList);  
              }
          }
      }
      
  • test call

    The initOrder request to access gmall-order-web will call UserService to obtain the user address; if the call is successful, it means that order can call the remote UserService.

    【premise】

    You must open the Zookeeper registration center, dubbo monitoring center, run the provider service, and then run the test code

    Test code:

    @SuppressingWarning("resource")
    public static void main(String[] args) throws IOException {
          
          
    		ClassPathXmlApplicationContext ioc = 
    				new ClassPathXmlApplicationContext("classpath:consumer.xml");
    		OrderService orderService=ioc.getBean(OrderService.class);
            orderService.initOrder();
    		System.in.read();// 按任意键退出 
    	}
    

    The running screenshot is as follows
    [External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-x5NZ44hG-1628218502775)(../Typora/Typora-images/image-20210804161826613.png)]
    [External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-xDtSroTx-1628218502777)(../Typora/Typora-images/image-20210804161942839.png)]

Integration with springboot

Three ways to integrate springboot and dubbo:

(1) Import dubbo-starter, configure properties in application.properties, and use @EnableDubbo to enable dubbo services in the main class, use @Service to expose services and @Reference to reference services.

(2) Keep the dubbo.xml configuration file. Import dubbo-starter, mark @ImportResource on the main class to import the configuration file of dubbo

@ImportResource(locations="classpath:provider.xml")

(3) Configuration class (API configuration)

Mark the @EnableDubbo(scanBasePackages="xxx") annotation on the main configuration class, then mark @Configuration on the configuration class, and map each tag of dubbo.xml to the configuration method XxxConfig.

Case optimization:

premise:When running the consumer main class, the zookeeper registration center, the dubbo monitoring center service, and the service provider main class must be enabled to ensure that they are running

  • service provider

    Step 1: Introduce the public interface package, dubbo-spring-boot-starter

    <dependency>
    			<groupId>com.pinkhub</groupId>
    			<artifactId>gmall-api</artifactId>
    			<version>0.0.1-SNAPSHOT</version>
    </dependency>
    <dependency>
    			<groupId>com.alibaba.boot</groupId>
    			<artifactId>dubbo-spring-boot-starter</artifactId>
    			<version>0.2.0</version>
    </dependency>
    

    Step 2: Mark @EnableDubbo on the main configuration class to enable itannotation baseddubbo service

    Step 3: Configure dubbo in application.properties

    dubbo.application.name=user-service-provider
    dubbo.registry.address=127.0.0.1:2181
    dubbo.registry.protocol=zookeeper
    
    dubbo.protocol.name=dubbo
    dubbo.protocol.port=20881
    
    #监控中心协议,如果为protocol="registry",表示从注册中心发现监控中心地址,否则直连监控中心 
    dubbo.monitor.protocol=registry
    

    Step 4: Register the exposed service,Use the service annotation provided by dubbo

    @Service   //使用dubbo提供的service注解,注册暴露服务
    public class UserServiceImpl implements UserService {
          
          
        @Override
        public List<User> getUserAddressList(String userId) {
          
          
            User user1 = new User(1, "屈明明", "河南省洛阳市洛龙区", "212", "13137041655");
            User user2 = new User(2, "屈明明", "陕西省渭南市白水县", "212", "13759699712");
            List<User> users = Arrays.asList(user1, user2);
            return users;
        }
    }
    
  • service consumer

    Step 1: Introduce public interface package, dubbo-spring-boot-starter, spring-boot-starter-web

    Step 2: Mark **@EnableDubbo** on the main configuration class and enable itannotation baseddubbo service

    Step 3: Configure dubbo in application.properties

    #dubbo-monitor-simple端口号8080,为了避免与tomcat的冲突,需要改下tomcat端口号
    server.port=8088
    
    dubbo.application.name=order-service-consumer
    dubbo.registry.address=zookeeper://127.0.0.1:2181
    dubbo.monitor.protocol=registry
    

    the fourth step:Reference remote service, use the **@reference** annotation provided by dubbo to reference the remote service

    @Service
    public class OrderServiceImpl implements OrderService {
          
          
        @Reference
        public UserService userService;
        @Override
        public List<User> initOrder(String userId) {
          
          
            List<User> userList = userService.getUserAddressList(userId);
            return userList;
        }
    }
    

    Step 5: Write the control class and make a remote call

    @Controller
    public class OrderController {
          
          
        @Autowired
        OrderService orderService;
        @ResponseBody
        @RequestMapping("/user")
        public List<User> getUserAddress(@RequestParam("uid") String uid){
          
          
            List<User> users = orderService.initOrder(uid);
            return users;
        }
    }
    
  • run screenshot

    Browser access: http://localhost:7001/ Enter dubbo monitoring center
    [External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-UjyioGIQ-1628218502778)(file://F:/Typora/Typora-images/image-20210804225547451.png? lastModify=1628065556)]

    Browser access: http://localhost:8088/user?uid=212
    [External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-KPm8Ycyz-1628218502780)(../Typora/Typora-images/image-20210804225106392.png)]

8.3.8 High availability

High availability: through design, reduce the time that the system cannot provide services

zookeeper downtime

Phenomenon: The zookeeper registration center is down, but consumers can still call the provider's remote service.

reason:robustness

  • The downtime of the monitoring center does not affect the use, but part of the sampling data is lost

  • After the database is down, the registration center can still provide service list query through the cache, but cannot register new services

  • The registration center is a peer-to-peer cluster, and when any one goes down, it will automatically switch to another

  • After the registration center is completely down, the service provider and the service consumer can still communicate through the local cache

  • The service provider is stateless, and if any one goes down, it will not affect the use

  • After the service provider is all down, the service consumer application will be unavailable, and will reconnect infinitely waiting for the service provider to recover

    Dubbo direct connection refers to directly telling the consumer the address of the remote call provider.

dubbo direct connection

Dubbo direct connection means that in the absence of a registration center, such as zookeeper, the dubbo direct connection method is used to tell consumers the address of the remote call provider to realize remote calls.

@Reference(url=“127.0.0.1:20882”)//dubbo direct connection

load balancing mechanism

LoadBalance means load balancing in Chinese, and its responsibility is to "balance" network requests or other forms of load to different machines. Avoid the situation that some servers in the cluster are under too much pressure, while other servers are relatively idle. Through load balancing, each server can obtain a load suitable for its own processing capacity.

When cluster load balancing, Dubbo provides a variety of balancing strategies, the default is randomrandom calls. You can expand the load balancing strategy by yourself,

Learning documents: https://dubbo.apache.org/zh/docs/v3.0/references/features/loadbalance/

  • Random LoadBalance

    Weight-based random load balancing mechanism (dubbo default)
    [External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-Qg1sjD8F-1628218530430)(../Typora/Typora-images/image-20210805200930296.png)]

  • RoundRobin LoadBalance

    Weight-based round robin load balancing mechanism
    [External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-noECqQH3-1628218530437)(../Typora/Typora-images/image-20210805201023183.png)]

  • LeastActive LoadBalance

    The least active load balancing mechanism
    [External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-1wfupf4h-1628218530440)(../Typora/Typora-images/image-20210805201104839.png)]

  • ConsistentHash LoadBalance

    Consistent Hash-load balancing mechanism
    [External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-Rls4Oup7-1628218530441)(../Typora/Typora-images/image-20210805201202500.png)]

The custom load balancing mechanism takes polling as an example
[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-xAsEk5An-1628218530442)(../Typora/Typora-images/image-20210805213106764.png)]
Annotated version:

/************服务提供方*******************/
@Service(loadbalance = "roundrobin")
/*************服务消费方*******************/
@Reference(loadbalance = "roundrobin")

xml version:

<dubbo:service interface="..." loadbalance="roundrobin" />

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

Change provider weight
[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-KHZtVvhs-1628218530443)(../Typora/Typora-images/image-20210805215644997.png)]

service downgrade

When the pressure on the server increases sharply, according to the actual business situation and traffic, the server resources of non-critical services are released to ensure the normal operation or efficient operation of core services. Service downgrade can temporarily shield a non-critical service that has an error, and a return policy after downgrade needs to be defined.

passDubbo admin consoleimplementation, masking or fault tolerance.

  • Blocking: It means that the method call of the service by the consumer directly returns a null value, and does not initiate a remote call.

  • Fault tolerance: It means that after the method call of the service fails, the consumer returns a null value without throwing an exception

cluster fault tolerance

When the cluster call fails, Dubbo provides a variety of fault tolerance schemes, and the default is failover retry.

Cluster fault tolerance mode

  • Failover Cluster

    In case of failure, retry other servers. Use retries="2" to set the number of retries (excluding the first time).

    <dubbo:service retries="2" />
    
    <dubbo:reference retries="2" />
    
  • Failfast Cluster

    Fail fast, only one call is made, and an error will be reported immediately if it fails. Usually used for non-idempotent write operations, such as adding new records.

  • Failsafe Cluster

    Fail safe, when an exception occurs, just ignore it. Typically used for operations such as writing to audit logs.

  • Failback Cluster

    The failure is automatically recovered, and the failed request is recorded in the background and resent at regular intervals. Typically used for message notification operations.

  • Forking Cluster

    Call multiple servers in parallel, and return as long as one succeeds. Set the maximum number of parallelism by forks="2", which is used for operations with high real-time requirements

  • Broadcast Cluster

    Broadcast calls to all providers, one by one, if any one reports an error, it will report an error

cluster mode configuration

Follow the example below to configure cluster mode on the service provider and consumer

<dubbo:service cluster="failsafe" />
<dubbo:reference cluster="failsafe" />

Integrate hystrix

Hystrix aims to provide more robustness to latency and failures by controlling nodes that access remote systems, services, and third-party librariesfault toleranceability.

Step 1: Introduce dependencies

spring boot officially provides the integration of hystrix, adding dependencies directly in pom.xml

 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            <version>1.4.4.RELEASE</version>
</dependency>

Step 2: Mark the ==@EnableHystrix== annotation on the main class to enable the hystrix starter

Step 3: Configure the provider side @HystrixCommand to mark on the fault-tolerant method

Step 4: Configure @HystrixCommand(fallbackMethod = "error") on the consumer side. If it is fault-tolerant, call the custom error method


After learning these, congratulations that you have entered dubbo. If you want to learn more, you can go deep into the source code to understand the operating principle of dubbo. Brave Niu Niu is not afraid of difficulties, go ahead! ! !

Guess you like

Origin blog.csdn.net/weixin_44490884/article/details/119448992