dubbo study notes


Learning link: https://www.bilibili.com/video/BV1ns411c7jV?spm_id_from=333.337.search-card.all.click

1, MAVEN Engineering

Common interface GMALL interface

Interface contains bean object and service interface

for example

Provider

Contains the implementation class of the interface, does not contain the interface, and the interface is written in the public API

Interface and Bean object are introduced in POM Introduction and implementation of XML

<dependency>
    <groupId>com.atguigu.gmall</groupId>
    <artifactId>gmall-interface</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

Introducing dubbo dependency

<!-- https://mvnrepository.com/artifact/com.alibaba/dubbo -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dubbo</artifactId>
    <version>2.6.2</version>
</dependency>

Write provider 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://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <!--    1.Specify the current service/The name of the application (the same service name, not the same name as other servers) -->
    <dubbo:application name="userserviceprovider"></dubbo:application>

    <!--    2/Specify the location of the registry-->
    <dubbo:registry address="zookeeper://127.0.0.1:2181"></dubbo:registry>
    <dubbo:registry protocol="zookeeper" address="127.0.0.1:2181"></dubbo:registry>

    <!--    3.Communication rules and communication protocols-->
    <dubbo:protocol name="dubbo" port="20880"></dubbo:protocol>

    <!--    4.Exposure services ref:Point to the real implementation object of the service-->
    <dubbo:service interface="com.atguigu.gmall.service.UserService"
                   ref="userServiceImpl"></dubbo:service>

    <bean id="userServiceImpl" class="com.atguigu.gmall.service.impl.UserServiceImpl"></bean>
</beans>

The implementation class does not need to be changed and is completed normally

public class UserServiceImpl implements UserService {

    public List<UserAddress> getUserAddressList(String userId) {
        System.out.println("UserServiceImpl.....old...");
        // TODO Auto-generated method stub
        UserAddress address1 = new UserAddress(1, "3 / F, complex building, Hongfu science and Technology Park, Changping District, Beijing", "1", "Miss Li", "010-56253825", "Y");
        UserAddress address2 = new UserAddress(2, "Western Silicon Valley Building, Bao'an District, Shenzhen B 3rd floor of building (Shenzhen Branch)", "1", "Miss Wang", "010-56253825", "N");
        /*try {
			Thread.sleep(4000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
        return Arrays.asList(address1,address2);
    }

}

Consumer

Contains the implementation class of the interface, but does not contain the interface. The interface is written in the public API

Interface and Bean object are introduced in POM Introduction and implementation of XML

<dependency>
    <groupId>com.atguigu.gmall</groupId>
    <artifactId>gmall-interface</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/dubbo -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dubbo</artifactId>
    <version>2.6.2</version>
</dependency>

Write 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://code.alibabatech.com/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://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--    Scan package annotation-->
    <context:component-scan base-package="com.atguigu.gmall.service.impl"></context:component-scan>

    <dubbo:application name="userserviceprovider"></dubbo:application>

    <dubbo:registry address="zookeeper://127.0.0.1:2181"></dubbo:registry>

    <!--    Declare the interface of the remote service to be called: generate the remote service proxy-->
    <dubbo:reference interface="com.atguigu.gmall.service.UserService"
                     id="userService" check="false">
    </dubbo:reference>
</beans>

Implementation class

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    UserService userService;

    public List<UserAddress> initOrder(String userId) {
        System.out.println("user id,"+userId);
        //    1. Query the receiving address of the user
        List<UserAddress> addressList = userService.getUserAddressList(userId);
        return  addressList;
    }
}

2, SPRINBG-BOOT project

GitHub website: https://github.com/apache/dubbo-spring-boot-project

Dependent location

Common interface

UserAddress

public class UserAddress implements Serializable {

    private Integer id;
    private String userAddress; //User address
    private String userId; //User id
    private String consignee; //consignee
    private String phoneNum; //Telephone number
    private String isDefault; //Default address Y - yes N - no

    public UserAddress() {
        super();
        // TODO Auto-generated constructor stub
    }

    public UserAddress(Integer id, String userAddress, String userId, String consignee, String phoneNum,
                       String isDefault) {
        super();
        this.id = id;
        this.userAddress = userAddress;
        this.userId = userId;
        this.consignee = consignee;
        this.phoneNum = phoneNum;
        this.isDefault = isDefault;
    }

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUserAddress() {
        return userAddress;
    }
    public void setUserAddress(String userAddress) {
        this.userAddress = userAddress;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getConsignee() {
        return consignee;
    }
    public void setConsignee(String consignee) {
        this.consignee = consignee;
    }
    public String getPhoneNum() {
        return phoneNum;
    }
    public void setPhoneNum(String phoneNum) {
        this.phoneNum = phoneNum;
    }
    public String getIsDefault() {
        return isDefault;
    }
    public void setIsDefault(String isDefault) {
        this.isDefault = isDefault;
    }

}

OrderService

public interface OrderService {

    public List<UserAddress> initOrder(String userId);
}

UserService

public interface UserService {
    /**
	 * Return all shipping addresses by user id
	 * @param userId
	 * @return
	 */
    public List<UserAddress> getUserAddressList(String userId);

}

Provider

pom.xml

<!-- Dubbo Spring Boot Starter -->
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-spring-boot-starter</artifactId>
    <version>2.7.8</version>
</dependency>

<dependency>
    <groupId>com.atguigu.gmall</groupId>
    <artifactId>gmall-interface</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

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

dubbo.monitor.protocol=registry

Implementation class

@The function of DubboService annotation: expose the service so that it does not need to be configured in the xml file.

@DubboService
@Service
public class UserServiceImpl implements UserService {

    public List<UserAddress> getUserAddressList(String userId) {
        System.out.println("UserServiceImpl.....old...");
        // TODO Auto-generated method stub
        UserAddress address1 = new UserAddress(1, "3 / F, complex building, Hongfu science and Technology Park, Changping District, Beijing", "1", "Miss Li", "010-56253825", "Y");
        UserAddress address2 = new UserAddress(2, "Western Silicon Valley Building, Bao'an District, Shenzhen B 3rd floor of building (Shenzhen Branch)", "1", "Miss Wang", "010-56253825", "N");
        return Arrays.asList(address1,address2);
    }

}

springboot main program

@Function of enable dubbo annotation: enable dubbo function based on annotation

@EnableDubbo //Enable annotation based dubbo function
@SpringBootApplication
public class BootUserServiceProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(BootUserServiceProviderApplication.class, args);
    }

}

Consumer

Spring boot check spring web to import web related dependencies

<dependency>
    <groupId>com.atguigu.gmall</groupId>
    <artifactId>gmall-interface</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

<!-- Dubbo Spring Boot Starter -->
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-spring-boot-starter</artifactId>
    <version>2.7.8</version>
</dependency>

application.properties

server.port=8081

dubbo.application.name=consumer
dubbo.registry.address=zookeeper://127.0.0.1:2181
dubbo.monitor.protocol=registry

Implementation class

@Function of DubboReference annotation: Reference Service

@Service
public class OrderServiceImpl implements OrderService {

    //@Autowired
    @DubboReference
    UserService userService;

    public List<UserAddress> initOrder(String userId) {
        System.out.println("user id,"+userId);
        //    1. Query the receiving address of the user
        List<UserAddress> addressList = userService.getUserAddressList(userId);
        return  addressList;
    }
}

controller

@Controller
public class OderController {

    @Autowired
    OrderService orderService;

    @ResponseBody
    @RequestMapping("/initOrder")
    public List<UserAddress> initOrder(@RequestParam("uid")String userId){
        return orderService.initOrder(userId);

    }
}

springboot main program

@EnableDubbo
@SpringBootApplication
public class BootOrderServiceConsumerApplication {

   public static void main(String[] args) {
        SpringApplication.run(BootOrderServiceConsumerApplication.class, args);
    }
}

support

Interface proxy oriented high performance RPC call

Load balancing only

Automatic service registration and discovery

Highly expandable

Operation flow scheduling

Visual service governance and operation and maintenance

working principle

3, Start zookeeper

The first startup will lack zoo config

You need to add zoo_sample.cfg copy and rename it zoo cfg

Open zoo CFG modify configuration

Open zkServer

Start successful

Start zkCli server

4, Launch dubbo administration console

Premise: open zookeeper

Enter dubbo github website

https://github.com/apache/dubbo

Switch to master-0.2.0

Check the application. In the resources directory of the file Configuration of properties file

Similarly, skip to the Dubbo admin folder directory, open cmd on this page, and mvn clean package generates the target file

Copy the jar package in target

Put it in the directory you want to put, and run it with cmd command line in this directory

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

The browser opens localhost:7001

Login account root password root

dubbo 2.6 is a jar package 25 It used to be a war package

5, Case

UserService is commonly used, and cannot always put UserService and bean s into other module s, so subcontracting

In order to make orderservice call methods, dubbo transformation is used

springboot integration

springboot exposure service

Configure with annotations

@DubboService exposure service

Open @ EnableDubbo in the main program

An error occurred during startup, prompting the lack of package and adding dependency

The middle also failed because the dependency level is too high. Pay attention to the match between the zoo version and this one

<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-framework</artifactId>
    <version>2.12.0</version>
</dependency>

<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>2.12.0</version>
</dependency>

How to use interface annotations

@DubboReference

Three strides

1. Import dubbo

2,application. Write dubbo configuration in properties

3. Exposed services use @ DubboService annotation, and consumer services use @ Reference injection

6, Disposition

1. Configure priority

Public configuration Dubbo properties

2. Start check

Official documents: https://dubbo.apache.org/zh/docs/advanced/preflight-check/

Under normal circumstances, when there is no provider in the registration center, start the consumer, and the consumer program will report an error.

The startup check is to solve this problem.

  • By default, check = "true"
  • Turn off the startup check. Check = "false". The consumer skips the check provider and checks the service in the registry only when it is called

Example:

Set false in the xml file to configure a service

Configure all services without checking

Dubbo: other configurations of consumer

Official documents: https://dubbo.apache.org/zh/docs/references/xml/dubbo-consumer/

main program

package com.atguigu.gmall;

import com.atguigu.gmall.service.OrderService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;

public class MainApplication {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("consumer.xml");
        System.out.println("Call complete");
        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The running result is that the call is completed

If check=false is not set, an error will be reported

How to set check=false

@ dubboreference in springboot (version = 1.0.0, check = false)

3. Timeout & override configuration

Problem solving: the consumer uses the provider's method, which may take a long time. If it does not return for a long time, it will lead to a large number of thread blocking and performance degradation

You can specify the timeout attribute. If there is no response, it will be terminated immediately to prevent the thread from blocking

Timeout description

  • Unit: ms
  • Not set. The default value is 1000ms, i.e. 1s

Consumer configuration timeout

Configure priority

XML configuration official document: https://dubbo.apache.org/zh/docs/references/configuration/xml/

  • Precision first: method level first, interface level second, and global configuration third.
  • Consumer setting priority: if the level is the same, the consumer takes priority, followed by the provider.

Consumer method > provider method > consumer interface > provider interface > consumer global > provider Global

4. Number of retries

explain

Retries = "", number of retries, excluding the first call. 0 means no retry

principle

Idempotent function sets the number of retries [query, delete, modify, that is, each run has the same effect]

Reset times cannot be set for non idempotent functions [add]

Multiple providers

When multiple providers provide the same function, if the retry fails, the next provider will be replaced. Polling is used by default

5. Multi version

Official documents: https://dubbo.apache.org/zh/docs/advanced/multi-versions/

effect

Realize gray Publishing

Implementation mode

The provider writes multiple implementation classes and configures the version number

provider

Version 1 configuration

Version 2 configuration

Consumer

Call version 1 version = "1.0.0"

Call version 2 version = "2.0.0"

Random call version*

6. Local stub

Official documents: https://dubbo.apache.org/zh/docs/advanced/local-stub/

7. Three ways to integrate with Springboot

1) . import Dubbo starter in application To configure the properties, use @ Service [expose Service] and @ Reference [Reference Service]

Premise: enable dubbo function of annotation

1. Write @ EnableDubbo in the startup program

2. Or write Dubbo in the configuration scan. base-packages=com. atguigu. gmall

2) . keep dubbo xml configuration file

method:

Import dubbo starter. Use @ ImportResource to import the dubbo configuration file

Purpose:

Achieve precise configuration at the method level

3) How to use the annotation API

Manually create each component into the container

Official API configuration document: https://dubbo.apache.org/zh/docs/references/configuration/api/

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

(it is recommended to see the API documentation.)

7, High availability

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

1. zookeeper downtime and Dubbo direct connection

Question:

1) when zookeeper goes down, can consumers still call the service provider?

Yes, because there is a local cache to keep communication

2) can I call the service provider without zookeeper?

Yes, dubbo can connect directly to the service provider

2. Load balancing mode

Official documents: https://dubbo.apache.org/zh/docs/advanced/loadbalance/

The default is random call

1) Random load balancing mechanism based on weight

Call with probability according to the probability of each Provider according to the weight value

2) Weight based polling load balancing mechanism

The probability of each provider is allocated according to the weight, and the probability is scientifically realized by polling

3) Least active load balancing mechanism

Select the fastest provider according to the response speed of the last provider

4) Consistent hash load balancing mechanism

Enter according to the hash result,

Consumer settings

Polling mechanism configuration

Weighted polling configuration

Consumer @ Reference(loadbalance = "random")

1) static setting @ Service(weight = "") is set in the provider annotation

2) dynamic setting on the console

3. Service degradation

When the pressure on the server increases sharply, according to the actual business situation and traffic, some services and pages are not handled strategically or handled in a simple way, so as to release server resources to ensure the normal or efficient operation of core transactions.

You can temporarily mask a non critical service with error through the service degradation function, and define the return policy after degradation.

method

In consumer configuration

Shielding: the method calls of the consumer to the service directly return null values and do not initiate remote calls.

Fault tolerance: after the consumer's method call to the service fails, it returns null value without throwing exceptions.

4. Service fault tolerance & hystrix

Cluster fault tolerance documentation: https://dubbo.apache.org/zh/docs/advanced/fault-tolerent-strategy/

The default is failover retry

Cluster fault tolerance mode

mode

Integrate hystrix

1. Configure spring cloud starter Netflix hystrix

For consumers and providers

spring boot officially provides the integration of hystrix, which is directly in POM Add dependencies to XML:

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

Then add @ EnableHystrix on the Application class to enable the hystrix starter:

@SpringBootApplication  
@EnableHystrix  
public class ProviderApplication  {     
2. Configure Provider side

Add @ HystrixCommand configuration on Dubbo's Provider so that the sub call will pass through the Hystrix agent.

@Service(version = "1.0.0")  
public class  HelloServiceImpl implements HelloService {   
 @HystrixCommand(commandProperties =
   {@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
    @HystrixProperty(name ="execution.isolation.thread.timeoutInMilliseconds", value =  "2000") })    
    @Override
    public String sayHello(String name) 
    {   // System.out.println("async  provider received: " + name);      
        // return "annotation: hello,  " + name;      
        throw new  RuntimeException("Exception to show hystrix enabled.");    
    }  
}  


3. Configure Consumer side

For the Consumer side, you can add a layer of method calls and configure @ HystrixCommand on the method. When there is an error in the call, it will go to the call with fallbackMethod = "reliable".

@Reference(version =  "1.0.0")    
private HelloService demoService;     

@HystrixCommand(fallbackMethod = "reliable")    
public String doSayHello(String name) {      
   return demoService.sayHello(name);    }   

public String reliable(String name) 
   { return "hystrix fallback  value";}  

principle

To be added

Tags: Dubbo rpc

Posted by lukeurtnowski on Thu, 14 Apr 2022 01:20:15 +0930