[Spring Cloud] Understand the microservice architecture, split a simple Demo to implement remote invocation of services


Preface

With the rapid development of information technology and changing business needs, the traditional monolithic architecture has gradually revealed its limitations in dealing with complexity and flexibility. In order to better adapt to the needs of modern enterprises, microservice architecture emerged as the times require. Microservices architecture is an approach to building systems by breaking applications into small, independent services.

The main motivations for using microservices architecture include:

  1. Flexibility and scalability: Microservices allow the entire system to be divided into multiple small services, each focused on a specific business function. This modular design makes the system more flexible and can be quickly expanded or reduced according to needs.

  2. Independent deployment and maintenance: Microservices can be deployed independently, and each service has its own database and operating environment. This means that modifications or updates to one service will not have an impact on other services, simplifying deployment and maintenance complexity.

  3. Technology diversity: Microservices allow the use of different technology stacks and programming languages ​​to implement different services. This flexibility allows teams to choose the tools best suited for specific tasks rather than being limited to a single technology stack.

  4. Fault isolation and fault tolerance: The failure of a single microservice will not affect the operation of the entire system. Other services in the system can still work normally, thus improving the system's fault tolerance and availability.

  5. Team autonomy: Each microservice can be independently developed and maintained by a small team, improving the team's autonomy. This distributed team structure helps accelerate development cycles and respond to business changes.

Overall, microservices architecture aims to provide a more agile, maintainable and scalable approach to software development and deployment, allowing enterprises to better adapt to rapidly changing market and business environments. At the same time, this is also the reason why we need to learn microservice architecture.

1. Understanding microservices

1.1 The evolution of service architecture: from monolith to microservices

With the continuous development of Internet technology, software architecture is also constantly evolving, gradually evolving from the earliest monolithic architecture to a distributed architecture, and now to today's more flexible and scalable microservice architecture. In the process of this evolution, the architectural design gradually moves from simplicity to complexity, and the coupling degree between services gradually decreases, thus better adapting to changing business needs.

Monolithic architecture

The earliest software development adopted a monolithic architecture, in which all functions were integrated into a project and eventually packaged as a whole for deployment. The advantage of this architecture is its simplicity and relatively low deployment cost. However, since all functions are coupled together, when the system becomes large and complex, maintenance and expansion become extremely difficult, and the disadvantages of the monolithic architecture are gradually revealed.

Monolithic architecture

advantage:

  • Simple architecture
  • Low deployment cost

shortcoming:

  • High degree of coupling
  • Difficult to maintain
  • Poor scalability

Distributed architecture

In order to solve the problem of monolithic architecture, distributed architecture gradually evolved. In a distributed architecture, the system is split according to business functions, and each business module is developed and deployed as an independent project. The advantage of this is that it reduces the coupling between services, making the system easier to maintain and expand. However, distributed architecture also brings new problems, such as service splitting granularity, service cluster address maintenance, remote calls between services, etc.

Distributed architecture

advantage:

  • Reduce service coupling
  • Conducive to service upgrade and expansion

question:

  • Service split granularity
  • Service cluster address maintenance
  • Remote calls between services
  • Service health status awareness

Microservice architecture

Microservice architecture is a more flexible and advanced form of distributed architecture. In the microservice architecture, the system is split into multiple tiny services, each of which corresponds to a unique business capability and implements a single responsibility. These services communicate through well-defined interfaces and are deployed and maintained independently. The characteristics of microservice architecture include service orientation, autonomy, strong isolation, etc.

Features of microservice architecture:

  • Single responsibility: each service is responsible for a unique business capability
  • Service-oriented: services expose businesses to the outside world through interfaces
  • Autonomy: Team, technology, data, and deployment are all independent
  • Strong isolation: service calls are isolated, fault-tolerant, and downgraded

The advantage of microservice architecture is that it can better adapt to business changes and improve the maintainability and scalability of the system. However, microservice architecture also brings some new challenges, such as service governance, distributed transactions, complexity of service invocation, etc., which need to be addressed during design and implementation.

Generally speaking, the evolution of service architecture is to better adapt to complex and changing business needs. Choosing the appropriate architecture depends on specific business scenarios and needs.

1.2 Comparison of microservice technologies: Dubbo, Spring Cloud, Spring Cloud Alibaba

The implementation of microservice architecture cannot be separated from the support of corresponding technical frameworks. In China, Dubbo, Spring Cloud and Spring Cloud Alibaba are three microservice technology stacks that have attracted much attention. Let’s compare them in depth on some key aspects:

Technology comparison

Dubbo Spring Cloud Spring Cloud Alibaba
Registration center Zookeeper、Redis Eureka、Consul Nacos、Eureka
Service remote call Dubbo protocol Feign (HTTP protocol) Dubbo、Feign
Configuration center none Spring Cloud Config Nacos、Spring Cloud Config
service gateway none Spring Cloud Gateway、Zuul Spring Cloud Gateway, Nacos Gateway
Service monitoring and protection Dubbo-admin (weaker functionality) Hystrix Sentinel

1. Dubbo:

Dubbo is a high-performance, lightweight open source RPC (remote procedure call) framework provided by Alibaba. It is mainly used to solve communication problems between distributed services, allowing remote calls to be easily made between different services. Dubbo provides a series of core functions of distributed systems such as service registration and discovery, load balancing, and service invocation.

main feature:

  1. Service registration and discovery: Dubbo provides support for a variety of service registration centers, including Zookeeper, Redis, etc., for managing and discovering service instances.

  2. Load balancing: Dubbo has a variety of built-in load balancing algorithms, which can select appropriate load balancing methods according to actual scenarios to improve system availability and performance.

  3. Service invocation: Dubbo supports multiple invocation methods, including synchronous invocation, asynchronous invocation, unicast invocation, broadcast invocation, etc., to meet the needs of different business scenarios.

  4. Service fault tolerance: Dubbo provides a variety of fault tolerance mechanisms, including timeout retry, automatic switching on failure, fast failure, etc., which enhances the stability of the system.

  5. Interface proxy-oriented: Dubbo uses interface proxy to make service calls and supports multiple protocols, including Dubbo protocol, HTTP protocol, etc.

2. Spring Cloud

Spring Cloud is a set of distributed system development tools based on Spring Boot, used to build microservice architecture. It provides a series of solutions and components to help developers easily build, connect and manage microservices. Spring Cloud provides a series of tools such as service registration and discovery, configuration management, load balancing, circuit breakers, gateways, etc., making it easier to build and manage distributed systems.

main feature:

  1. Service registration and discovery: Spring Cloud supports multiple service registration centers, including Eureka, Consul, Zookeeper, etc., for dynamic discovery and registration of services.

  2. Configuration management: Spring Cloud Config provides centralized configuration management and supports dynamic refresh of configuration, making the configuration more flexible.

  3. Service invocation: Spring Cloud uses Feign for declarative service invocation, simplifying remote invocation between services.

  4. Load balancing: Spring Cloud integrates the Ribbon load balancer, which can achieve load balancing among multiple services.

  5. Circuit breaker: Spring Cloud uses Hystrix to provide circuit breaker support to prevent fault propagation in distributed systems.

3. Spring Cloud Alibaba:

Spring Cloud Alibaba is a microservice framework based on Spring Cloud and Alibaba's technical system. It integrates some open source components of Alibaba based on Spring Cloud and provides more functions integrated with the Alibaba Cloud ecosystem.

main feature:

  1. Service registration and discovery: Spring Cloud Alibaba supports Nacos as the service registration center and is also compatible with Eureka.

  2. Configuration management: Use Nacos as the configuration center to achieve centralized configuration management.

  3. Service invocation: Spring Cloud Alibaba supports both Dubbo protocol and Feign for service invocation.

  4. Load balancing: Integrated with Alibaba's load balancing solutions, such as Ribbon and Nacos.

  5. Service fault tolerance: Use Sentinel to implement flow control, circuit breaker and degradation to improve system stability.

Generally speaking, Dubbo, Spring Cloud and Spring Cloud Alibaba are all frameworks designed to solve communication, configuration, service discovery and other issues in distributed systems. They have some differences in implementation. You can choose the appropriate framework according to actual needs. .

Choice of company needs

  • Spring Cloud + Feign: Suitable for scenarios where the Spring Cloud technology stack is used, the service interface adopts Restful style, and the service call adopts Feign method.

  • Spring Cloud Alibaba + Feign: Suitable for scenarios where the Spring Cloud Alibaba technology stack is used, the service interface adopts Restful style, and the service invocation adopts Feign method.

  • Spring Cloud Alibaba + Dubbo: Suitable for scenarios where the Spring Cloud Alibaba technology stack is used, the service interface adopts the Dubbo protocol standard, and the service invocation adopts the Dubbo method.

  • Dubbo original mode: suitable for scenarios based on the old Dubbo technology system, the service interface adopts the Dubbo protocol standard, and the service call adopts the Dubbo method.

When choosing a technology stack, you need to make trade-offs and choices based on specific business needs, team experience, and the characteristics of the technology stack. Different technology stacks have different advantages and applicable scenarios, so all factors need to be comprehensively considered in actual applications.

1.3 Spring Cloud: The essence of microservice framework

What is Spring Cloud

Spring Cloud is a set of development tools for quickly building microservice architecture in distributed systems. It provides a series of tools and components that allow developers to easily build various microservices in distributed systems and solve some common problems in microservice architecture, such as service discovery, configuration management, load balancing, and circuit breakers. wait.

Spring Cloud features

Spring Cloud combines multiple microservice-related components to form a complete microservice framework. Here are some of the core features provided by Spring Cloud:

Spring Cloud features

The above figure shows some core functions provided by Spring Cloud. The functions of each function are as follows:

  1. Service registration discovery: Through service registration centers (such as Eureka, Consul, Nacos, etc.), microservice instances can register and discover other services, thereby realizing dynamic discovery and communication between services.

  2. Unified configuration management: Spring Cloud Config allows application configurations to be centrally stored in the configuration server, making configuration modification and management more convenient, while supporting dynamic refresh of configurations.

  3. Service remote invocation: Spring Cloud provides Feign as a declarative service invocation tool, which simplifies remote invocation between services. Developers only need to define interfaces and use annotations for configuration.

  4. Unified gateway routing: Spring Cloud Gateway and Zuul are two commonly used service gateway components. They are responsible for routing, filtering and forwarding of requests, and provide unified entrances and exits.

  5. Service link monitoring: Spring Cloud Sleuth is used in combination with Zipkin to implement distributed tracking and monitoring of microservice systems, helping to discover and solve performance problems in the system.

  6. Flow control, degradation, and protection: By using Sentinel or Hystrix, you can implement flow control, degradation, and circuit breaker protection for microservices, improving the stability and fault tolerance of the system.

Together, these capabilities build a complete microservices ecosystem, making it easier for developers to build, manage, and monitor complex distributed systems. These functional components of Spring Cloud make the microservice architecture more powerful, flexible, and better able to adapt to different business needs.

Version compatibility between Spring Cloud and Spring Boot

Spring Cloud is a microservices framework built on Spring Boot, so its version compatibility with Spring Boot is a key issue. Spring Cloud is usually released with a specific version of Spring Boot to ensure compatibility between the two.

When choosing a Spring Cloud version, you need to check the official Spring Cloud documentation to understand the compatibility of this version with the corresponding Spring Boot version. This helps ensure the stable operation of the microservices system while taking advantage of the latest features of Spring Boot.

For example, you can click on the reference document of a specific SpringCloud version at : https://spring.io/projects/spring-cloud#learn , and you can find the corresponding Spring Boot version there.

For example:

Click to view the reference document of Spring Cloud 2021.0.8, and you will find that the corresponding Spring Boot version is 2.6.15:

2. Microservice splitting cases and remote calls

2.1 Prepare Spring Cloud Demo code

In order to demonstrate the splitting and remote calling of microservices, we prepared a simple Spring Cloud Demo code, which contains two modules: order-service(Order module) and user-service(User module).

The project structure is as follows:

Project structure

In this Demo, the order module is responsible for querying order information, and the user module is responsible for querying user information.

Code to query order information:

@Autowired
private OrderService orderService;

@GetMapping("{orderId}")
public Order queryOrderByUserId(@PathVariable("orderId") Long orderId) {
    
    
    // 根据id查询订单并返回
    return orderService.queryOrderById(orderId);
}

Code to query user information:

/**
 * 路径: /user/110
 *
 * @param id 用户id
 * @return 用户
 */
@GetMapping("/{id}")
public User queryById(@PathVariable("id") Long id) {
    
    
    return userService.queryById(id);
}

Example: Query order information

Example: Query user information

Through the above example, we found a problem: when the order module queries order information, the user information is null. In order to solve this problem, we need the order module to call the interface of the user module /user/{userId}to obtain user information and fill the user information into the order.

In this case, we involve the splitting and remote calling of microservices:

  • Microservices should be split according to business modules to achieve a single responsibility to avoid repeated development of the same business.
  • Microservices can expose business as interfaces for use by other microservices.
  • Different microservices should have independent databases.

In the next steps, we can continue to improve this example and demonstrate how to use Spring Cloud to split and remotely call microservices.

2.2 Case: Query complete order information based on order ID in microservices

The requirements for this case are: while querying the order based on the order ID, return the user information to which the order belongs, as shown in the following figure:

Analysis of remote calling methods:

When we request order information, the order module not only needs to request the order information, but also needs to request the corresponding user information from the user module based on the user ID of the order. Finally, the results of all requests are merged and returned to the front end.

The steps for remote calling of microservices are as follows:

  1. Register RestTemplate
    in order-servicethe startup class :OrderApplicationRestTemplate
@SpringBootApplication
public class OrderApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(OrderApplication.class, args);
    }
    
    @Bean
    public RestTemplate restTemplate(){
    
    
        return new RestTemplate();
    }
}
  1. Service remote callRestTemplate

Method to modify order-servicein :OrderServicequeryOrderById

@Autowired
private OrderMapper orderMapper;

@Autowired
private RestTemplate restTemplate;

public Order queryOrderById(Long orderId) {
    
    
    // 1. 查询订单
    Order order = orderMapper.findById(orderId);

    // 2. 查询用户
    // 2.1 构建查询用户的 url
    String url = "http://localhost:8081/user/" + order.getUserId();
    // 2.2 使用 RestTemplate 远程调用查询用户
    User user = restTemplate.getForObject(url, User.class);

    // 3. 封装 user 信息
    order.setUser(user);

    // 4.返回
    return order;
}

After all the code has been modified, restart order-servicethe service and query the order again:


At this point, remote calling of microservices is implemented.

2.3 RestTemplate tool description

1. What is RestTemplate?

RestTemplate is a client tool provided by Spring for accessing REST services. It simplifies communication with RESTful services and provides a variety of convenient methods, including GET, POST, PUT, DELETE and other request methods.

The main features of RestTemplate include:

  1. Simplify HTTP requests: RestTemplate encapsulates HTTP requests, and can send and receive HTTP requests through simple method calls.

  2. Supports multiple request methods: RestTemplate supports multiple HTTP request methods such as GET, POST, PUT, DELETE, etc. to meet different business needs.

  3. Convenient parameter passing: RestTemplate provides a variety of ways to pass request parameters, including URL variables, request bodies, request headers, etc.

  4. Simplified error handling: RestTemplate encapsulates HTTP responses to facilitate handling of different response status codes and error messages.

2. RestTemplate sample code

The following is a simple example code that uses RestTemplate to send a GET request:

import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class RestClient {
    
    

    public static void main(String[] args) {
    
    
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();

        // 定义请求地址
        String url = "https://jsonplaceholder.typicode.com/posts/1";

        // 发送 GET 请求,并获取响应结果
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);

        // 获取响应状态码
        int statusCode = responseEntity.getStatusCodeValue();

        // 获取响应体
        String responseBody = responseEntity.getBody();

        // 输出结果
        System.out.println("Status Code: " + statusCode);
        System.out.println("Response Body: " + responseBody);
    }
}

In the above code, we use the RestTemplate getForEntitymethod to send a GET request and obtain the response status code and response body. This is just a simple example, RestTemplate also provides many other methods to support richer HTTP request and response operations.

Guess you like

Origin blog.csdn.net/qq_61635026/article/details/133356337