[SpringCloud microservice project actual combat-mall4cloud project (2)]——mall4cloud-gateway

代码地址
github site
fork selfgithub source item
gitee site
forkselfgitee primitive item

System architecture and gateway introduction

Insert image description here
As can be seen from the figure, after the user side and static layer pass through the access layer (nginx+firewall), they will reach the back-end service. The first thing to pass is the gateway layer. The gateway layer is implemented by springCloud gateway2+load balancing.

Gateway introduction

The gateway layer in the microservices architecture acts as the gatekeeper of the microservices architecture, responsible for processing requests, managing security, implementing filtering and transformation, performing routing and load balancing, and other tasks. By centrally managing these functions, the gateway can simplify client access to microservices and provide some critical non-business functions to ensure high availability, performance and security of the entire system.

Request routing: The gateway acts as the entry point for all requests entering the microservices system. It routes requests to the appropriate microservice instance based on some predefined rules. This routing can be based on the requested URI, HTTP method, request headers, query parameters and other conditions.

Load balancing: The gateway can be integrated with a load balancer to ensure that requests are evenly distributed to multiple microservice instances, thereby improving system availability and performance. This helps avoid single points of failure and handle large volumes of requests efficiently.

Security: The gateway layer is typically responsible for handling authentication and authorization, ensuring that only authenticated and authorized requests can access protected microservices. It can integrate single sign-on (SSO), OAuth, JWT verification and other security mechanisms.

Monitoring and logging: The gateway can record request and response information for monitoring and logging. This helps track system performance issues, troubleshooting, and security audits.

Filtering and conversion: The gateway can process requests and responses through filters and perform some non-business functions, such as request and response conversion, request retry, current limiting, caching, data encryption, etc. These filters can add, modify, or remove parts of requests and responses during request processing.

Versioning and routing strategies: The gateway layer allows the implementation of versioning strategies so that different versions of microservices can coexist and requests can be routed to the appropriate microservice version based on the version number.

Error handling: The gateway can handle errors in microservices and provide meaningful error responses instead of exposing internal errors to clients.

Caching: The gateway can cache commonly used responses, thereby reducing the burden on back-end microservices and improving response time.

Current limiting: The gateway can control traffic and limit the request rate to microservices to prevent too many requests from overloading the system.

Gateway layer code

Dependency introduction

under the pom file in the code. You can see that the following main dependencies have been introduced
Insert image description here
①③: Introducing nacos registration center and configuration center dependencies
②: Introducing loadbalancer dependencies
④: Introduce gateway dependency

bootstrap configuration

Insert image description here
①: The port is 8000
②: Application name: read from the maven configuration as mall4cloud-gateway, after specifying the name, If no configuration is made, the default configuration file name is mall4cloud-gateway.yaml. After connecting to the configuration center, this default configuration file will be automatically obtained.
③: nacos registration center address, port 8848
④: Configuration center address, the same address from the previous step is introduced
⑤: Use the default namespace,
⑥: used for the above shared-configs:application-dev.yml, get this configuration from nacos
Next, take a look at the configuration of nacos

nacos configuration

The application-dev.yml configuration is some public connection information and will not be explained. The following is the individual configuration of the gateway.

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allow-credentials: true
            allowed-headers: "*"
            # 半个月内都允许
            max-age: 1296000
            # 测试环境,全部允许
            allowedOriginPatterns: "*"
            # allowedOrigins:
              # - "http://localhost:9527"
              # - "http://localhost:9527"
              # - "http://localhost:9528"
              # - "http://localhost:9529"
              # - "http://:9527"
            allowedMethods:
              - GET
              - POST
              - PUT
              - OPTIONS
              - DELETE
      discovery:
        locator:
          # 开启服务注册和发现
          enabled: true
          # 不手动写路由的话,swagger整合不了...

Gateway configuration handles cross-domain issues

spring.cloud.gateway.globalcors.cors-configurations: This configuration item specifies the CORS configuration information. It is a Map, where the key is the URL matching pattern and the value is the CORS configuration.
[/**]: This is a URL matching pattern, which means matching all URLs. This means that this CORS configuration will be applied to all request paths.
allow-credentials: true: Allow credential information, such as cookies or HTTP authentication information, to be included in CORS requests.
allowedOriginPatterns: * Allowed source (domain) patterns. In a test environment, set to * to allow any origin. Typically, you can also use the allowedOrigins attribute to specify specific allowed origins.
allowed-headers: * : Allowed request headers. Here, * means allow any request header.
max-age: 1296000: Set how long the browser can cache CORS responses, in seconds. Here, set to half a month (1296000 seconds). That is to say, you can access directly without going through cors request during the validity period
allowedMethods: Allowed HTTP request methods include GET, POST, PUT, OPTIONS and DELETE, etc.

This configuration is used to configure global CORS rules in Spring Cloud Gateway, allowing front-end applications to access the gateway's API from any source (in a test environment) and allowing requests that include credential information. This helps solve the problem of cross-domain requests and allows the front-end to communicate cross-domain with the back-end API.

gateway routing assertion configuration

	routes:
        - id: mall4cloud-rbac
          uri: lb://mall4cloud-rbac
          predicates:
            - Path=/mall4cloud_rbac/**
          filters:
            - RewritePath=/mall4cloud_rbac(?<segment>/?.*), $\{
    
    segment}
        - id: mall4cloud-auth
          uri: lb://mall4cloud-auth
          predicates:
            - Path=/mall4cloud_auth/**
          filters:
            - RewritePath=/mall4cloud_auth(?<segment>/?.*), $\{
    
    segment}

routes: Gateway routing configuration
Examples are as follows:
Route with id mall4cloud-rbac:in array format
id: mall4cloud-rbac: Defines the unique identifier of this route.
uri: lb://mall4cloud-rbac: Specifies the load balancing address of the target service to which the request should be routed. Here, lb://mall4cloud-rbac means routing requests to a service named mall4cloud-rbac, using a load balancer to select a specific instance.
predicates: Defines the request matching rule. The Path attribute is used here. means only This routing rule will only be applied when the requested path matches /mall4cloud_rbac/**. will be routed to the target service lb://mall4cloud-rbac

The result of accessing the login interface through the gateway is as follows:
Insert image description here
The result is consistent with the direct access to the login interface, that is, the routing is successful
Insert image description here
The above result It can be understood as /mall4cloud_rbac/** routing to lb://mall4cloud-rbac service
Here we introduce the commonly used routing assertion factories. The official website has the following 11 assertion methods
Insert image description here

gateway route filtering configuration

In Spring Cloud Gateway, you can use filters to handle traffic entering or leaving the gateway.Requests and responses. These filters allow you to perform various operations at different stages of the request and response, such asmodifying request headers, response headers, request bodies, logging, etc.. Filters can be used for global configuration or for specific routing rules
The following is the filter configuration of the project
Insert image description here
filters: Some routing filters are defined, here Use the RewritePath filter, which rewrites the requested path. Specifically, it will extract the path part after /mall4cloud_rbac and append it to the URI of the target service to achieve rewriting of the request path.

  • RewritePath: Specifies the name of the filter factory to be used, here is the filter that rewrites the request path.
  • /mall4cloud_auth: This is the part of the original request path to match. If the requested path matches this part, then this filter will be triggered.
    (?/?.*): This is a regular expression capture group, which is used to capture the path part after /mall4cloud_auth in the request path and store it in a segment named segment in variables.
  • ,${segment}: This is the format of the rewritten target path. It adds the portion of the path following /mall4cloud_auth in the original request path to the target path.

For example, if the original request path is /mall4cloud_auth/users, then this filter will rewrite the request path to /users and route the request to the appropriate backend service. This way, the /mall4cloud_auth part of the request path is removed.

In addition, spring also provides a variety of filter factories, for example:
Insert image description here
Other filters can be set according to specific needs. The documentation can be viewed in the gateway official website: Create a global filter class named MyGlobalFilter, inherit the GlobalFilter interface, and implement the filter method to define filtering logic, example The code is as follows:
Insert image description here
You can also add global filters, for example:

import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    
    

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    
    
        // 这里可以编写过滤逻辑,例如修改请求或响应
        return chain.filter(exchange); // 调用链中的下一个过滤器
    }

    @Override
    public int getOrder() {
    
    
        return 0; // 定义过滤器的执行顺序,0表示最高优先级
    }
}

Summarize

Through the gateway, the project can process requests, implement filtering and transformation, perform routing and load balancing. Among these contents, there are usually many configurations. If the project requires the use of a gateway, you can choose an appropriate solution based on the functionality of the gateway.

Guess you like

Origin blog.csdn.net/qq_40454136/article/details/132819693