Service Gateway, Spring Cloud, Gateway Fusion, Current Limitation, Retry a little Classroom (Multi-shore College)

Posted by sobbayi on Thu, 12 Sep 2019 05:52:37 +0200

A filter that modifies the request path

StripPrefix Filter

StripPrefix Filter is a request path interception function that we can use to forward special services.

application.yml is configured as follows:

spring:
  cloud:
    gateway:
      routes:
      - id: nameRoot
        uri: http://nameservice
        predicates:
        - Path=/name/**
        filters:
        - StripPrefix=2

The example of this configuration above shows that StripPrefix=2 represents the number of interception paths when the request path matches to / name /** and the string containing name and the back is removed and forwarded, so that when the request path matched to the back end of the request / name/bar/foo is configured, the request path becomes http://nameservice/foo.

We are also testing in the cloud-gateway-eureka project, modifying application.yml as follows:

spring:
  cloud:
     routes:
     - id: nameRoot
       uri: lb://spring-cloud-producer
       predicates:
       - Path=/name/**
       filters:
       - StripPrefix=2

Restart the cloud-gateway-eureka project after configuration. Access address: http://localhost:8888/name/foo/hello page will alternately display:

hello world!
hello world smile!

Consistent with the direct access address http://localhost:8888/hello, the name/foo/in the request path has been intercepted.

PrefixPath Filter

PrefixPath Filter acts as the opposite of Strip Prefix, adding a part of the prefix before the URL path

> spring:   cloud:
>     gateway:
>       routes:
>       - id: prefixpath_route
>         uri: http://example.org
>         filters:
>         - PrefixPath=/mypath

You can come down to the test, not the demonstration here.
Speed-Limited Router

Speed limitation is one of the most commonly used methods in high concurrency scenarios, which can effectively guarantee the overall stability of services. Spring Cloud Gateway provides a Redis-based flow limitation scheme. So we first need to add the corresponding dependency package spring-boot-starter-data-redis-reactive.

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>

Redis address and current limit configurations need to be added to the configuration file

spring:
  application:
    name: cloud-gateway-eureka
  redis:
    host: localhost
    password:
    port: 6379
  cloud:
    gateway:
     discovery:
        locator:
         enabled: true
     routes:
     - id: requestratelimiter_route
       uri: http://example.org
       filters:
       - name: RequestRateLimiter
         args:
           redis-rate-limiter.replenishRate: 10
           redis-rate-limiter.burstCapacity: 20
           key-resolver: "#{@userKeyResolver}"
       predicates:
         - Method=GET
filter The name must be RequestRateLimiter
redis-rate-limiter.replenishRate: How many requests are allowed to be processed per second
redis-rate-limiter.burstCapacity: The capacity of the token bucket, the maximum number of requests allowed to be completed in one second
key-resolver: Use SpEL Reference by name bean

Set the current limit policy in the project and create the Config class.

public class Config {

    @Bean
    KeyResolver userKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
    }
}

Limit the current according to the user field in the request parameter, or according to the request IP address, as follows:

@Bean
public KeyResolver ipKeyResolver() {
    return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
}

In this way, the gateway can limit the flow of requests according to different strategies.
Fuse router

In the previous Spring Cloud series, you should have a certain understanding of fusing. If you don't know, you can read this article first: fuse Hystrix.

Spring Cloud Gateway can also take advantage of Hystrix's fuse feature to downgrade services when traffic is too high, and we should first add dependencies to the project.

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

Configuration example

spring:
  cloud:
    gateway:
      routes:
      - id: hystrix_route
        uri: http://example.org
        filters:
        - Hystrix=myCommandName

After configuration, gateway will use myCommandName as the name to generate HystrixCommand objects for fuse management. If you want to add fused callback content, you need to add some configuration.

spring:
  cloud:
    gateway:
      routes:
      - id: hystrix_route
        uri: lb://spring-cloud-producer
        predicates:
        - Path=/consumingserviceendpoint
        filters:
        - name: Hystrix
          args:
            name: fallbackcmd
            fallbackUri: forward:/incaseoffailureusethis

FallbackUri: forward:/ incaseoffailure ureusethis configures the path to be tuned when fallback is invoked, and when the fallback calling Hystrix is invoked, the request is forwarded to the URI of / incaseoffailure ureusethis.
Retry router

RetryGateway Filter is a Gateway Filter Factory provided by Spring Cloud Gateway for request retry

Configuration example:

spring:
  cloud:
    gateway:
      routes:
      - id: retry_test
        uri: lb://spring-cloud-producer
        predicates:
        - Path=/retry
        filters:
        - name: Retry
          args:
            retries: 3
            statuses: BAD_GATEWAY

Retry Gateway Filter controls retries, statuses, methods, and series through these four parameters.

Retries: number of retries, default value is 3
 statuses: HTTP status return code, for values, see: org. spring framework. http. HttpStatus
 methods: Specify which method requests need to retry the logic. The default value is the GET method. Refer to the value: org. spring framework. http. HttpMethod
 series: State code configuration for some columns, refer to: org. spring framework. http. HttpStatus. series. The retry logic will only be performed for a certain segment of the status code. The default value is SERVER_ERROR, and the value is 5, which is 5XX (the status code at the beginning of 5). There are five values.


Students who want to study in depth can join the QQ group discussion oh, QQ group discussion: 984370849 706564342 welcome to join the discussion.

We have high-level complete resource note sharing, our group also has IT professionals, can quickly solve the problem here to find solutions.

Yes, we are waiting for you to share our experiences and our common but different stories.

Topics: Spring Redis