SpringCloud series: How to communicate between microservices

Author's other platforms:

| CSDN:blog.csdn.net/qq_41153943

| Nuggets: juejin.cn/user/651387…

| Zhihu: www.zhihu.com/people/1024…

| GitHub: github.com/JiangXia-10…

This article has a total of 2662 words and is expected to read for 13 minutes

What are microservices

Microservice is a kind of distributed architecture. Distributed architecture is actually to split the service, and springcloud only solves the service governance problem in the split process.

In the monolithic architecture, we write all the services together, and the coupling degree of the complex code of the business will become higher and higher, which is not convenient for future upgrade and maintenance.

Therefore, it is often necessary to split these services. When splitting microservices, a single application will be split into many independent projects according to the business function modules. Each project completes part of the business functions, and then develops and deploys independently. . These independent projects become a microservice. And then form a service cluster.

For example, the most common e-commerce system is composed of many services, such as order service, user function, commodity service, payment service, etc. In the previous monolithic architecture period, these modules were implemented using a monolithic architecture, so the degree of coupling will be quite High, development will be very difficult, especially in the later maintenance and expansion, which is difficult and troublesome. But if you use microservice development, you can develop each service as a single application, then the order service is developed as a microservice, and the user service is also developed as a microservice.

Then the microservices of these independent services constitute the entire e-commerce system. In this way, each service can be deployed in a cluster according to specific business needs, which not only reduces the coupling of services, but also facilitates maintenance and upgrade of services.

What is a registration center

The previous articles mentioned the registration center in microservice development. We know that a business often requires multiple services to complete together. For example, when a request is sent, it first calls service A, and then service A may call service B, service B calls service C, and so on.

Therefore, when the business logic becomes more and more complex, the call relationship between these services will become more and more complicated. At this time, a registration center is needed to record the ip, port, service name and the ability of each service. Completed function. In this way, when these services need to call each other, there is no need to record the ip and port of the service to be called, but only need to go to the registration center to find it.

Common registration centers include nacos (you can refer to SpringCloud: Building Nacos Services and Service Discovery ), eureka (you can refer to SpringCloud Series: Service Registration and Discovery Components-Eureka (Part 1) , SpringCloud Series: Service Registration and Discovery Components-Eureka (Part 2) ), consul (you can refer to the SpringCloud series: Service Registry Component—consul ), and zookeeper (you can refer to: Zookeeper Tutorial: Getting Started ).

Then, in addition to the registration center, the most important thing about the service call of microservices is the communication problem between various services. Let's learn about communication issues between microservices together today.

Microservice Communication

Communication between microservices can be divided into two types according to the type of communication:

One is synchronous communication: the main methods are HTTP REST and RPC. The HTTP REST method refers to the use of the http protocol for data transfer, and the data format is in the json format; RPC is a remote procedure call, and the message format is in the binary format.

http rest belongs to the application layer in the osi seven-layer model, while rpc belongs to the transport layer, so the efficiency of rpc is more efficient than that of http rest.

There is also asynchronous communication: there are usually two modes of asynchronous messaging, one is agentless mode: it means that the C side directly sends the message to the P side without being recovered, and when the P side needs to recover, it is asynchronous Communication, the C terminal will not be blocked, and the P terminal will reply the processing result to the C terminal according to the received information after processing. This method is relatively niche and is mainly suitable for some asynchronous notification scenarios. The other is: use a message broker, where you need to use some message middleware, such as RocketMQ, kafka, etc. This method can be used in a wide range of scenarios, and there are many mature solutions in the industry. The decoupling of microservices can be well achieved by using asynchronous message communication.

Today I mainly talk about the synchronous communication method. The asynchronous one mainly relies on some message middleware. I will publish an article to introduce this method when I learn middleware later. The synchronous communication method in springcloud mainly uses the http rest method.

The Spring framework provides an httpclient object RestTemplate to initiate an http request.

Example demo

Create two independent sub-projects here, namely orders and users, and use the consul registration center to register with it. The specific creation process is the same as the microservice project created in the SpringCloud series: Service Registry Component—consul. You only need to modify some configurations, such as port number and service name. The specific source code is at the end of the article . References can be downloaded as needed.

The project structure is as follows:

picture

Start the two projects separately, open the management page of consul, and the two microservices have been registered in the consul registration center respectively.

picture

The next step is to develop the call logic between services. Service calls are actually interface calls, so here you need to add controller interfaces to the user and order services respectively. The controller in order is as follows:

@RestController
@RequestMapping("order")
public class OrderController {
    private static  final Logger  logger = LoggerFactory.getLogger(OrderController.class);
    @GetMapping("order")
    public String order(){
        logger.info("order module is running....");
        return "order module is running";
    }
}
复制代码

What needs to be used here is to call the interface in the order in the user service, so the controller in the user is as follows:

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

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @GetMapping("user")
    public String user(){
        logger.info("user module is running....");
//        在user服务中调用order服务,并且接受返回值
        //创建一个RestTemplate对象
        RestTemplate restTemplate = new RestTemplate();
        //调用order接口
        String result = restTemplate.getForObject("http://localhost:8084/order/order",String.class);
        logger.info("调用order服务成功....",result);
        return "user服务中调用order服务,结果为:"+result;
    }
}
复制代码

Here the resttemplate object is used to make interface calls and accept return objects.

The development is over here, and the core is the use of the resttemplate object. Then start the user and order projects separately. First enter the address bar:

http://localhost:8084/order/order
复制代码

Enter, the result is as follows:

picture

Indicates that the interface call of the order service is successful. But here is the direct call. Next, test the interface that calls the order service in the user service, so enter in the address bar:

http://localhost:8083/user/user
复制代码

Enter, the result is as follows:

picture

The console output is as follows:

picture

Indicates that calling the interface in the order service in the user service is successful!

Summarize

It can be found that using the resttemplate object to make service calls is actually very simple, that is, use the getForXX method provided by resttemplate, and then accept the returned object. So it can be summarized as follows:

1. Simple to use, directly supports request/response communication,

2. It is highly testable and can be tested through a browser or curl command.

3. There is no need for intermediate agents, which simplifies the system architecture

But through the above code, it can be found that its shortcomings are also obvious:

1. The client must know the specific location (URL) of the server, which needs to be written in the request method;

2. The path url for invoking the service request is directly written in the method and is hard-coded, so the load balancing requested when serving the cluster cannot be achieved;

3. Because it is hard-coded, if subsequent iterations lead to path changes, it is not conducive to subsequent maintenance and expansion work.

4. It may lead to reduced usability. The communication process requires both the client and the server to be online at the same time, and any faulty communication will fail.

But for load balancing of requests, springcloud provides the corresponding load balancing component -ribbon. spring cloud ribbon is a client load balancing tool based on http and tcp. It is implemented based on netflix ribbon. Through spring cloud encapsulation, it allows us to automatically convert service-oriented resttemplate requests into client load balancing service calls.

Due to the limited length of the article, the learning about ribbon will continue later.

The source code of this article is on github: github.com/JiangXia-10…

related suggestion

Guess you like

Origin blog.csdn.net/qq_41153943/article/details/125964683