I heard about Ali’s micro service RPC framework Dubbo long ago when CHOOSING the micro service architecture, which was compared with Spring Cloud’s HTTP protocol call architecture. It is found that dubbo’s RPC framework has high learning cost, strong code invasion, incomplete ecology and the need to integrate multiple external components. Therefore, Spring Cloud family bucket with relatively weak performance is selected.

Until the emergence of Spring Cloud Alibaba, Nacos was used as a service for discovery and registration, compatible with HTTP calls using Feign and RPC calls using Dubbo.

Why does Spring Cloud need RPC

In Spring Cloud microservices, most developers use Feign components provided by the government for internal service communication. This kind of declarative HTTP client is very simple, convenient and elegant to use, and is independent of development platform and language. However, in general, HTTP does not enable the KeepAlive function. That is, the KeepAlive function is a short connection. The disadvantage of a short connection is that a TCP connection needs to be established for each request, which makes the KeepAlive function inefficient.

Providing REST API services externally is a good thing, but if the internal calls are also made using HTTP, the performance will be poor. The Feign component used by Spring Cloud by default makes internal service calls using HTTP protocol. In this case, It would be a good choice if we used RPC calls for internal services and REST apis for external services.

Refer to:Dubbo is a perfect combination with Spring Cloud

Using the Dubbo Spring Cloud using the internal RPC protocol calls is a near zero cost transformation.

1. System structure

  • cloud-gatewayAs the gateway of the Cloud cluster, external routing is used for forwardinghttpProtocol used by internal service invocationsdubboagreement
  • cloud-userandcloud-mqBetween remote callsdubboagreement
  • useNacosAs aService registration and discoveryandConfiguration centerThe service of
  • useSentinelAs a service roomhttpanddubboThe flow control service invoked

The directory structure

├─ Cloud-admin ├─ Cloud-gateway ├─ Cloud-mq service ├─ Cloud-provider service Interface ├─ cloud-user service ├─ Cloud-gateway Service ├─ Cloud-mq Service ├─ Cloud-provider Service Interface ├─ cloud-user serviceCopy the code

Realization of service interface provider

1. Service interface definition

public interface UserProvider {
    UserDTO checkUser(String userName, String password);
    UserDTO findByUserName(String userName);
}

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserDTO implements Serializable {
    String userName;
    String realName;
    String password;
}

Copy the code
  • A service interface is a contract between a service provider and a consumer that contains a method transport object (DTO) for the service. Since the introduction of multiple application services is involved, it is best to separate them into modules
  • DTO objects must be implementedSerializableinterface

2. The introduction ofdubbopackage

POM

 <dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-dubbo</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Copy the code

Spring-boot-starter -actuator is also required

3. Service interface implementation

import org.apache.dubbo.config.annotation.Service;

@Service
public class UserProviderImpl implements UserProvider {

    @Autowired
    private UserService userService;

    @Override
    public UserDTO checkUser(String userName, String password) {

        User user = userService.checkUser(userName, password);
        returnUserConvertor.toDTO(user); }}Copy the code

@ Service must be org. Apache. Dubbo. Config. The annotation. Service

4. Configure the Dubbo service

spring:
  main:
    allow-bean-definition-overriding: true
    
dubbo:
  scan:
    base-packages: fun.barryhome.cloud.provider   Dubbo service implementation class scan base package
  protocols:
    dubbo:
      name: dubbo   # Dubbo protocol name
      port: - 1      # port indicates the protocol port (-1 indicates the increment port, starting from 20880).

  registry:
    address: spring-cloud://localhost       Mount to the Spring Cloud registry
Copy the code

Connection failure may occur after startup, which does not affect service

java.net.ConnectException: Connection refused (Connection refused)
	at java.net.PlainSocketImpl.socketConnect(Native Method)At java.net.AbstractPlainSocketImpl ~ [na: 1.8.0 comes with _111].doConnect(AbstractPlainSocketImpl.java:350)At java.net.AbstractPlainSocketImpl ~ [na: 1.8.0 comes with _111].connectToAddress(AbstractPlainSocketImpl.java:206)~ [na: 1.8.0 comes with _111]Copy the code

Service caller implementation

1. Import dependency packages

<! -- Service interface -->
<dependency>
    <groupId>fun.barryhome</groupId>
    <artifactId>cloud-provider</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <scope>compile</scope>
</dependency>
 <dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-dubbo</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Copy the code

2. Invoke the service interface

import org.apache.dubbo.config.annotation.Reference;

public class UserController {

    @Reference
    private UserProvider userProvider;

    @GetMapping(value = "/sessionUser")
    public UserDTO sessionUser(HttpServletRequest request) {

        String userName = request.getHeader("X-User-Name");
        if (Strings.isEmpty(userName)) {
            throw new RuntimeException("No user found");
        }

        returnuserProvider.findByUserName(userName); }}Copy the code

3. Configure the Dubbo service

dubbo:
  cloud:
    subscribed-services: cloud-user   The service name of the service provider
  consumer:
    check: false
    loadbalance: "leastactive"    Minimum active load balancing

  registry:
    Mount to the Spring Cloud registry
    address: spring-cloud://localhost
Copy the code

Dubo.consumer.check: Used to check whether the service provider is running properly at startup. If not, the caller cannot be started

Dubbo. Consumer. Loadbalance: load balancing strategy

  • RandomLoadBalance: random, according to the weight set random probability
  • ConsistentHashLoadBalance: consistent hashing algorithm
  • Leastactive VeloadBalance: Minimum active load balancing
  • RoundRobinLoadBalance: According to the weight of the rotation

Four,

  1. A long connection is used between services. In normal operation, it takes a period of time for the provider to switch over after a node breaks downsentinelTo control fast switching between available nodes
  2. Using Dubbo for remote calls, internal calls provide performance and are relatively simple
  3. withsentinelCoordination, reasonable use of load strategy, can achieve more functions, such as gray release, version control and so on
  4. The performance improvements make it possible to increase the call chain, enabling smaller granularity of microservice splitting and composition

V. Source code

Gitee.com/hypier/barr…

Please pay attention to my official number