Spring Cloud Study Notes [Gateway-Gateway]

Gateway overview

What is Gateway

Spring Cloud Gateway is a lightweight gateway solution in the Spring Cloud ecosystem. It is built on technologies such as Spring Framework 5, Spring Boot 2, and Project Reactor, and can be used to build efficient and scalable microservice architectures.
insert image description here
The main function of Spring Cloud Gateway is to route and forward the request from the client. It can judge the target service of the request according to the requested URL, request header, request parameters and other information, and forward the request to the corresponding service. At the same time, Spring Cloud Gateway also provides some common filters, such as routing, current limiting, retrying, caching, etc. These filters can help developers implement some common functions, such as access control, security authentication, etc.

specific function

  1. Routing function: Spring Cloud Gateway can route and forward according to the requested URI, request header, request parameters and other information, and supports multiple routing rules, such as Path Route, Host Route, Predicate Route, etc.
  2. Filter function: Spring Cloud Gateway provides some built-in filters, such as Request Header, Response Header, Rewrite Path, etc., and also supports developers to customize filters.
  3. Dynamic routing: Spring Cloud Gateway supports dynamic routing, which can dynamically add, delete and modify routing rules without restarting the gateway instance.
  4. Fuse function: Spring Cloud Gateway supports fuses, which can fuse back-end services to prevent service avalanches and improve system availability.
  5. Current limiting function: Spring Cloud Gateway can limit current based on QPS, concurrency and other indicators to prevent the system from being overloaded.
  6. Security authentication function: Spring Cloud Gateway supports various security authentication mechanisms, such as OAuth2, JWT, etc.
  7. Log and monitoring functions: Spring Cloud Gateway provides a wealth of log and monitoring functions, which can easily monitor the operation status and processing performance of the gateway, and facilitate troubleshooting and performance optimization.
  8. Integrate Spring Cloud: Spring Cloud Gateway can easily integrate various components in the Spring Cloud system, such as Eureka, Consul, Zipkin, etc., to provide a complete solution for the microservice architecture.

The difference between Gateway and Zuul

Both Gateway and Zuul are gateway components provided by Spring Cloud. The main differences between them lie in the following aspects:

  1. The technology stack is different: Gateway is based on Spring WebFlux and Reactor framework, using asynchronous non-blocking I/O operations, while Zuul is based on Servlet API and blocking I/O operations.
  2. Different performance: Gateway has better performance than Zuul, mainly because it uses asynchronous non-blocking I/O operations, which can provide higher concurrent performance and throughput.
  3. Different functions: Gateway provides a wealth of routing rules and filters, and supports functions such as dynamic routing and current limiting, while Zuul is relatively simple and only supports some basic routing and filtering functions.
  4. Applicable scenarios are different: Gateway is suitable for high-performance and high-scalability scenarios, while Zuul is suitable for some small and medium-sized projects.
  5. Maintenance and support are different: Spring Cloud Gateway is a new generation of gateway components of the Spring Cloud team, which has received better official maintenance and support, while Zuul has been gradually phased out and is no longer officially maintained and updated.

Three Core Concepts

Route

Route specifies how the request should be routed, including the target URL, routing rules and some optional filters. By configuring Route, all requests can be mapped to corresponding microservice instances.

Predicate

Predicate defines a logical condition for matching requests from clients. It can be matched based on the requested URL, request header, request parameters and other information, and only requests that meet the conditions will be routed to the corresponding microservices.

Filter

Filter is used to perform some additional logic before or after routing requests, such as authentication, flow control, log monitoring, etc. Gateway provides many built-in filters, and also supports developers to customize filters.

Gateway workflow

insert image description here

The workflow of Spring Cloud Gateway can be simply summarized as: receiving requests, matching routes, executing filters, and forwarding requests. Specifically, its workflow is as follows:

  1. Receive request: When the client sends a request to Gateway, Gateway will receive the request and forward it to the route processor for processing.
  2. Matching route: Gateway will match according to the requested URI, request header, request parameters and other information to find the appropriate Route.
  3. Execute filters: Gateway will execute a series of Filters in the order configured in Route to process and convert requests. Filters can modify, transform, and enhance requests before or after they are routed to backend services.
  4. Forwarding request: After the filter processes the request, Gateway will forward the request to the corresponding backend service for processing. After the backend service returns a response, Gateway will forward the response to the client.

It should be noted that the core process of Gateway is asynchronous and non-blocking, and it adopts a Reactor-based responsive programming model, which can provide higher concurrent performance and throughput. At the same time, Gateway also supports functions such as dynamic routing and current limiting, which can meet the needs of different scenarios.

Gateway DEMO configuration

yml file configuration routing

Create new Gateway module cloud-gateway-gateway9527
insert image description here
pom.xml

<dependencies>
        <!--gateway-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <!--eureka-client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
        <dependency>
            <groupId>com.atguigu.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <!--一般基础配置类-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

application.yml
mainly focuses on the configuration of the gateway, defines a routing rule user_routh, and can access the interface of the user service through the gateway:

server:
  port: 9527

spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      routes:
        - id: user_routh #user_routh    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: http://localhost:9001          #匹配后提供服务的路由地址
          predicates:
            - Path=/user/info/**         # 断言,路径相匹配的进行路由

eureka:
  instance:
    # 配置eureka的状态显示
    hostname: localhost
    instance-id: ${
    
    eureka.instance.hostname}:${
    
    spring.application.name}:${
    
    server.port}
  client: #服务提供者provider注册进eureka服务列表内
    service-url:
      register-with-eureka: true
      fetch-registry: true
      defaultZone: http://eureka7001.com:7001/eureka

Start class GateWayMain9527

@SpringBootApplication
@EnableEurekaClient
public class GateWayMain9527 {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(GateWayMain9527.class, args);
    }
}

Start the project test
Direct access to port 9001
insert image description here
Access through gateway 9527, or jump to 9001
insert image description here

Configuration class configuration routing

For example, create a new configuration class and configure routing to Baidu News. . .

@Configuration
public class GateWayConfig {
    
    
    /**
     * 配置了一个id为route-name的路由规则,
     * 当访问地址 http://localhost:9527/guonei时会自动转发到地址:http://news.baidu.com/guonei
     *
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    
    
        RouteLocatorBuilder.Builder routes = builder.routes();

        routes.route("path_route_atguigu",
                r -> r.path("/guonei")
                        .uri("http://news.baidu.com/guonei")).build();

        return routes.build();
    }

    @Bean
    public RouteLocator customRouteLocator2(RouteLocatorBuilder builder) {
    
    
        RouteLocatorBuilder.Builder routes = builder.routes();
        routes.route("path_route_atguigu2",
                r -> r.path("/guoji")
                        .uri("http://news.baidu.com/guoji")).build();
        return routes.build();
    }
}

Realize dynamic routing through microservice names

Our routing uri was a hard-coded address before.
insert image description here
Let’s change it to a service name. When there are multiple services on the server side, it can be called with load balancing.
It should be noted that the protocol of uri is lb, which means that the load balancing function of Gateway is enabled.
After the update:
uri : lb://lf-user
insert image description here
test:
two port service polling calls of 9001 and 9011
insert image description here
insert image description here

Predicate

What is Predicate

In Spring Cloud Gateway, Predicate refers to the logical conditions used to match requests. It is a functional interface used to determine whether to process the current request based on the requested URL, request header, request parameters and other information. Predicate can be configured through Gateway routing rules to match different routes according to different request conditions.

In Spring Cloud Gateway, Predicate can be matched according to the requested path, request parameters, request header, request method and other information. It can implement various complex request matching logic, such as fuzzy matching, regular expression matching, multiple condition matching combination matching etc.

Common Route Predicate

  1. Path: Match according to the requested path, supporting Ant-style path matching.
    For example, the following configuration indicates that only when the requested path starts with /api/user, the current Route will be matched:
spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://user-service
          predicates:
            - Path=/api/user/**

  1. Query: Match according to the requested parameters, and support the matching of parameter names and parameter values.
    For example, the following configuration indicates that the current Route will be matched only when the request parameter contains userId and the value of userId is not empty:
spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://user-service
          predicates:
            - Query=userId,*
  1. Method: Match according to the method of the request, and support the matching of HTTP request methods.
    For example, the following configuration indicates that only when the request method is GET, the current Route will be matched:
spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://user-service
          predicates:
            - Method=GET
  1. Host Predicate: Match according to the request's Host header. For example, Host=example.com means to match all requests whose Host header is example.com.
  2. RemoteAddr Predicate: Matches based on the requested remote IP address. For example, RemoteAddr=192.168.0.1/24 means to match all requests whose IP addresses are in the 192.168.0.1 subnet.
  3. After Predicate: Match according to the time of the request. For example, After=2021-10-01T00:00:00.000Z means to match all requests that occur after 2021-10-01.
  4. Weight Predicate: Load balancing is performed according to the weight of the request. For example, Weight=group1,2 means that the request is sent to the service group named group1, and there are 2 instances participating in load balancing.

These Route Predicates can be used in combination to implement more complex request matching logic. At the same time, Spring Cloud Gateway also supports custom Route Predicate, and developers can implement the Predicate interface according to actual needs to achieve more flexible and customizable gateway services.

Filter

What is Filter

In Spring Cloud Gateway, Filter refers to a component used to modify or process requests and responses before or after the request is routed to the target service. It can modify, transform, enhance or intercept requests or responses as needed.

Filter is one of the core components of Spring Cloud Gateway. It can implement many gateway functions, such as routing forwarding, request/response logging, request authentication, request flow limiting, request retry, etc. Filter is the key to realizing the custom function of the gateway. Filter can be customized according to actual needs to meet specific business needs.

The Filter interface defines two main methods: filter() and order(). Among them, the filter() method is the specific implementation logic of the filter, which is used to process the request; the order() method is the execution order of the filter, and the smaller the value, the earlier the execution.

Spring Cloud Gateway has many built-in Filters, such as RequestRateLimiterGatewayFilterFactory, RetryGatewayFilterFactory, AddRequestHeaderGatewayFilterFactory, HystrixGatewayFilterFactory, etc. In addition, developers can also customize Filter according to actual needs by implementing the GatewayFilter or GlobalFilter interface.

Commonly used GatewayFilter

  1. AddRequestHeader: used to add request headers.
  2. RemoveRequestHeader: used to remove the request header.
  3. AddResponseHeader: Used to add response headers.
  4. RemoveResponseHeader: Used to remove response headers.
  5. SetPath: used to set the request path.
  6. RewritePath: used to rewrite the request path.
  7. Retry: Used for request retry.
  8. RequestRateLimiter: Used to request rate limit.
  9. Hystrix: for fuse protection.
  10. ModifyResponseBody: Used to modify the response body.
  11. ModifyResponseHeader: used to modify the response header.
  12. SaveSession: Used to save the Session during request processing.
  13. ForwardPath: used to forward the request to the specified path.

custom filter

The custom global MyLogGateWayFilter
mainly implements two interfaces implements GlobalFilter, Ordered

Specific code:

@Component
public class MyLogGateWayFilter implements GlobalFilter, Ordered {
    
    

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    
    
        System.out.println("time:" + new Date() + "\t 执行了自定义的全局过滤器: " + "MyLogGateWayFilter" + "hello");

        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if (uname == null) {
    
    
            System.out.println("****用户名为null,无法登录");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 这个返回的数值越小,上面的filter优先级就越高
     *
     * @return
     */
    @Override
    public int getOrder() {
    
    
        return 0;
    }

}

test

With the parameter uname, it can be accessed normally. insert image description here
Without uname, an error is reported
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/qq_33129875/article/details/129727780