Basic use of microservice-gateway

I. Introduction

Microservice architecture has become one of the mainstream paradigms of modern software development. It allows development teams to break down complex applications into small, autonomous service units for easier development, deployment, and maintenance. However, as the number of microservices increases, managing and maintaining these services becomes increasingly complex. At this time, the microservice gateway becomes an indispensable component to improve maintainability, security and performance.

Two, gateway gateway

1. What is a microservice gateway?

A microservice gateway is an intermediate layer between the microservice architecture and external clients. It acts as the entry point to the microservice architecture and handles all communication with clients. A microservice gateway has multiple responsibilities, including routing requests, load balancing, authentication, authorization, logging, and security. It can be seen as the gatekeeper of the microservice architecture, used to secure and manage microservice clusters.
First, let’s take a look at a picture to show the position of our gateway in our project. You can see that the gateway is at the core of our entire project. All requests from our front-end to access the back-end must be forwarded through the gateway.
insert image description here

2. The importance of gateways under the microservice architecture

2.1, no gateway

If there is no gateway, under the microservice architecture, all the microservices of our front-end access to the backend must pass through different ports or IPs. The following figure shows that the four microservices of user, product, shop, and order are deployed on a virtual machine , respectively occupying different ports, if the front-end wants to access all the microservices on the back-end, it needs to access through four different ports.
insert image description here

2.2, there is a gateway

If we use the gateway, there are also four microservices. We only need to access all the microservices by accessing the gateway. Now it is immediately clear the importance of the gateway in the microservice architecture.
insert image description here

3. The function of the gateway

Spring Cloud Gateway is a reverse proxy and routing tool for building microservice architectures.

  • Routing: Spring Cloud Gateway allows you to define routing rules to map incoming requests to different microservice instances. Routing rules are usually defined based on conditions such as the requested URL path, request header, and HTTP method. This allows you to direct them to different backend microservices based on different requests, achieving dynamic request routing.

  • Request Filtering: Gateway provides request filters that allow you to modify requests or perform specific actions before they reach backend microservices. You can use these filters to add request headers, modify request bodies, perform authentication, limit request rates, transform responses, and more.

  • Load Balancing: Spring Cloud Gateway integrates load balancing functions, which can distribute requests to multiple backend microservice instances to ensure high availability and performance. It supports multiple load balancing algorithms, such as round robin, weight, etc., and you can configure them according to your needs.

  • Circuit Breaker: Gateway has a circuit breaker pattern for handling failures of backend microservices. When the backend microservice is unavailable, Gateway can quickly switch to an alternate service or return a friendly error response instead of waiting for a long time for a timeout.

  • Dynamic Routing: Gateway supports dynamic routing, which means you can add, modify, or delete routing rules at runtime without restarting the service. This makes it more flexible to deal with traffic changes.

  • Request Retry: Gateway allows you to configure a request retry mechanism in response to transient failures of backend microservices. You can define the number of retries, intervals, and conditions to ensure that the request ultimately succeeds.

  • Rate Limiting: By using rate limiting filters, Gateway can limit the request rate per client or per IP address. This helps protect backend microservices from excessive request pressure.

  • Integration with Security: Gateway can be integrated with authentication and authorization systems to ensure only authorized users can access protected microservices. You can use Spring Security or another security framework to achieve this functionality.

  • Logging: Gateway has robust request and response logging, which is useful for troubleshooting and monitoring. You can configure the log level and output format to suit your needs.

  • Monitoring and Metrics: Gateway can integrate monitoring and metrics systems, such as Spring Cloud Sleuth and Micrometer, to monitor traffic and performance in real time and analyze them.

  • WebSocket support: Gateway supports the WebSocket protocol, allowing you to handle real-time bi-directional communication.

  • Custom Routing Rules: Gateway provides a rich extension mechanism that allows you to write custom routing rules and filters to meet specific needs.

4. Gateway actual combat

4.1, dependent configuration

Introduce related dependencies: SpringBoot, SpringCloud, SpringCloud gateway
First look at my project structure:
insert image description here

Here we introduce the related dependencies of SpringBoot and Spring Cloud in the parent pom

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.12.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<!--版本管理-->
<properties>
    <java.version>11</java.version>
    <spring-cloud.version>Hoxton.SR12</spring-cloud.version>
    <spring-cloud-alibaba.version>2.2.8.RELEASE</spring-cloud-alibaba.version>
</properties>

<!--依赖管理-->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>${spring-cloud-alibaba.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Introduce the related dependencies of the gateway in the child pom,注意:gateway中不要引入springboot的web模块,因为gateway使用的web服务器是netty不是tomcat,而springboot的web模块中默认配置的web服务器就是tomcat

<!--gateway相关依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- nacos服务注册/发现-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--nacos配置管理-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

4.2. Add gateway configuration

server:
  port: 9081
  servlet:
    context-path: /gateway-demo
spring:
  application:
    name: gateway-demo
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
        namespace: wangmengjie
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "*"
            allowedHeaders: "*"
            allowedMethods: "*"
      default-filters:
        - DedupeResponseHeader=Vary Access-Control-Allow-Origin Access-Control-Allow-Credentials, RETAIN_FIRST
      discovery:
        locator:
          enable: true #让gateway可以发现nacos中的微服务
      routes: #路由,数组[这里可以放置多个路由]
        #评分管理模块网关路由配置
        - id: user-router #当前路由标识-要求唯一,默认是UUID;
          uri: lb://user-demo #请求最终要被转发的地址;
          order: 1 #路由的优先级——数字越小,代表路由的优先级越高
          predicates: #断言:(条件判断——转发请求要满足的条件)
            - Path=/user-service/** #当请求路径满族path指定的规则时,此路由信息才会正常转发;
          filters: #过滤器,是在请求传递过程中对请求做一些手脚;
            - StripPrefix=1 #在请求转发之前去掉一层路径

4.3. Add gateway startup class

@SpringBootApplication(exclude = {
    
    DataSourceAutoConfiguration.class})
@EnableDiscoveryClient//开启nacos服务注册
public class GatewayApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(GatewayApplication.class,args);
    }
}

4.4. Check whether the project is started successfully

The project started successfully
insert image description here
and the nacos service registered successfully
insert image description here

4.5. Verify that the routing configuration is correct

Through the configuration file of the gateway, we can know that the assertion configured by the user module is user-service/**, indicating that when we visit localhost:9081/user-service/**, the request will be sent to our gateway. Then the gateway is configured through the uri, user-demo is the service name registered by the user module on nacos, the insert image description here
original interface address of the user module: http://localhost:9000/user/getAllUser
The interface address of the access gateway: http:// localhost:9081/user-service/user/getAllUser
The configuration of filters in the gateway configuration file will remove the first-level path before request forwarding, that is, the user module service information obtained through user-demo is: localhost:9000, In addition to the path forwarded by the request, the final request is: localhost:9000/user/getAllUser;
insert image description here

3. Summary

For the microservice system in the background of the project, each microservice will not be directly exposed to the user to call, if the user knows the ip: port number: url: access parameters of a certain service, they can directly access you, even malicious Access, etc., so a gateway is needed as a unified entrance for microservices. This article first introduces some basic integration + usage of the gateway. There is still a lot of knowledge about the gateway, such as cross-domain, filters, custom filters, global filters, etc., and then introduce them one by one.

If this blog is helpful to you, please remember to leave a message + like + bookmark.

Guess you like

Origin blog.csdn.net/wmj20001225/article/details/132625917