[SpringBoot integrates Nacos+Dubbo] Enterprise-level projects integrate microservice components to realize RPC remote calls

1. Demand

In the growing business needs, each project was developed independently at the beginning. Although the front and back ends are separated, each project does not interfere with each other. Later, due to certain requirements, the data of several projects need to be obtained interleaved with each other.

The initial idea was to integrate multiple data sources.

example

There are three projects A, B, and C, corresponding to the databases DBa, DBb, and DBc. Now the A project needs to operate the DBa and DBc databases at the same time.

At this time, the ideal is to call the RPC framework.

environment/version

IDEA2022.3.2
java11
SpringBoot 2.7.12-SNAPSHOT
Nacos 2.2.2

Note: If you use SpringBoot3.x or above, you need to use jdk17 or above, otherwise it will start an error.

Two, notice

2.1. What is RPC?

The full name of RPC is Remote Procedure Call, which is translated as remote procedure call. It is a computer network communication protocol used to communicate between different processes or computers, allowing them to call remote methods as if they were local methods.

Suppose you have an application that needs to call a function or method on another computer. Usually, you need to manually send requests and receive responses through network programming. RPC allows you to call remote functions directly like calling local functions, which simplifies the complexity of network programming.

Specifically, during the RPC communication process, the caller will send a request to the remote server just like calling a local method, and the request includes the method name and parameter list to be called. After receiving the request, the remote server will parse the request, call the corresponding method, and return the execution result to the caller. After the caller receives the response, it can process the result like a local function.

In layman's terms, RPC is like telling the remote party what you need to do when you are on the phone, and the other party will tell you the result after completion. In this way, you don't need to complete the task yourself. In this process, you only need to care about the tasks and results that need to be completed, and you don't need to care about the specific implementation method.

RPC is widely used in distributed systems, such as service calls in microservice architecture, remote procedure calls in Hadoop, etc. It can make distributed systems more simple, flexible and scalable.

2.2. What is Dubbo?

Background
The background of the birth of Dubbo can be traced back to 2011. At that time, Alibaba's internal distributed architecture and service governance were relatively mature. However, in the face of the growing business scale and complexity, the call and management between distributed services became a challenge. huge challenge. In this context, Dubbo came into being.

Dubbo was originally proposed and developed by Alibaba's engineers, aiming to provide a high-performance, reliable, and scalable RPC framework for Alibaba's internal distributed systems, helping Alibaba to better build distributed service architectures and implement services governance.

Later, as Dubbo gradually matured and was widely used within Alibaba, Alibaba decided to open source it and officially released the first version at the end of 2011, followed by versions 2.0 and 2.5 in 2012 and 2015, and 2019. Released version 2.7. Dubbo's open source and continuous update and iteration have attracted more and more users and developers to participate, and gradually become one of the most popular RPC frameworks in the Java ecosystem.

Today, Dubbo has been widely used in the distributed systems of Alibaba, Huawei, Netease and other enterprises, and has been widely recognized and supported by major Internet companies and communities at home and abroad.

In November 2018, Apache Dubbo became Apache's top-level project, which means that Dubbo has developed into a very mature, high-quality, and active community open source project. The addition of Dubbo has further strengthened Apache's position in the field of distributed systems, and has made great contributions to the development and promotion of distributed systems.

effect

Dubbo mainly includes three core modules:

Provider (service provider): The application that exposes the service and the method of providing the service.

Consumer (service consumer): The application that calls the remote service and the method of consuming the service.

Registry (Service Registry): The management center for service registration and discovery.

The workflow of the Dubbo framework is as follows:

1. The service provider starts and registers the services it provides with the registration center.

2. The service consumer starts and subscribes to the registration center for the services he needs.

3. The registration center returns the available service list to the service consumer.

4. The service consumer invokes the remote service.

5. The remote service provider responds to the request and returns the result to the service consumer.

6. The service consumer receives the response and completes the call.

2.3. What is Nacos?

Nacos is a dynamic service discovery, configuration management, and service governance platform built on the basis of cloud-native concepts. It was open sourced by the Alibaba open source team in 2018. It mainly solves the problems of service registration, discovery, configuration management and DNS service in distributed systems.

Nacos provides the following core functions:

1. Service registration and discovery: Nacos can help service providers automatically register services and report the health status of service instances to Nacos Server, and service consumers can query available service instances through Nacos.

2. Configuration management: Nacos provides a centralized configuration management function, supports functions such as dynamic configuration, version management, grayscale release, and monitoring, and can easily manage configuration information in a distributed system.

3. Service routing and load balancing: Nacos supports traffic management between service providers and consumers, dynamic update of routing rules, and multiple load balancing strategies.

4. DNS service: Nacos supports the provision of DNS services, and can use DNS to discover services without requiring other service discovery components.


Reminder: The default registration center on the Dubbo official website is Zookeeper, and the registration center used in this article is Nacos.

3. Ordinary SpringBoot project integration microservice component scheme (the author gives two kinds)

Option 1 (recommended)

Projects like the author's (see requirements ) have evolved to use microservice components because of development, rather than choosing a microservice architecture from the beginning. Just look at this part. Otherwise, see option two.

1. Import maven dependencies (consumers and providers are the same)

		<!--nacos-->
        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-client</artifactId>
            <version>2.2.2</version>
        </dependency>
        <!-- dubbo -->
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>3.2.0-beta.6</version>
        </dependency>

Add annotation @EnableDubbo to the startup class
insert image description here

2. Configure the application.yml file (consumer)

server:
  port: 8102
spring:
  cloud:
    nacos:
      server-addr: localhost:8848
dubbo:
  consumer:
    check: false
  application:
    name: dubbo-springboot-demo-consumer
  protocol:
    name: dubbo
    # 设置为-1表示自动配置可用端口
    port: -1
  registry:
    address: nacos://127.0.0.1:8848

Configure the application.yml file (provider)

server:
  port: 8105
spring:
  cloud:
    nacos:
      server-addr: localhost:8848
dubbo:
  application:
    name: dubbo-springboot-demo-provider
  protocol:
    name: dubbo
    port: -1
  registry:
    address: nacos://127.0.0.1:8848
    

3. Unified interface class (pay attention to the package name, because the package name of the consumer and the provider must be the same)

package com.example.astar.component;

public interface DemoService {
    
    

    String sayHello(String name);
}

4. Provider interface (add @DubboService annotation to the interface)

package com.example.astar.service.Impl;

import com.example.astar.component.DemoService;// 注意包名
import org.apache.dubbo.config.annotation.DubboService;

@DubboService
public class AstarServiceImpl implements DemoService {
    
    

    private static int flag = 0;

    @Override
    public String sayHello(String name) {
    
    
        String message = "你好啊! " + name + " =========》 " + flag++;
        return message;
    }
}

5. Consumer call interface

package com.example.astar.controller;

import com.example.astar.component.DemoService;//注意包名
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    
    

    @DubboReference
    private DemoService demoService;

    @GetMapping("/1")
    public String hello() {
    
    

        String result = demoService.sayHello("Astar");
        String re = "Receive result ======> " + result;
        System.out.println(re);
        return re;
    }
}

6. The call is successful

Start these two projects (consumer and provider), because the consumer is configured with check: false, so whichever project is started first is ok. The consumer's port is 8102, let's visit

http://localhost:8102/user/1

see below
insert image description here

Kind tips:

The fully qualified package name of DemoService is import com.example.astar.component.DemoService, which means that the bridge between the consumer and the provider comes from the same interface. We need to create exactly the same interface in the project to achieve Classes don't care. If the package names of the provider and consumer interfaces are different, the call will fail.

Speaking human words: even if the two projects are not under the same file, how can it be possible to use the same class? Here, as long as the class itself and the package name are the same, Dubbo will consider them the same.

Option II

This solution is based on the project that decided to use the framework of microservices at the beginning. Usually, we will divide it into several submodules like the following:

insert image description here

interface module

insert image description here
I am too lazy to talk about the steps, it is roughly the same as the first solution, the difference is the import of the public module interface:
just add submodules on the consumer and provider:

        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-samples-spring-boot-interface</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

Reminder: When packaging, the imported part of the submodule will be packaged together, don't worry, it can be used normally, and the rest will remain unchanged.

END


The vast sea of ​​people has a long way to go, and
it is only by concentrating on cultivation that you can be beautiful.
Take every step steadily and
wait for the flowers to bloom to see the truth.

Happy development!

Guess you like

Origin blog.csdn.net/qq_43813351/article/details/130560596