Microservices are so popular today that if you can’t learn a microservice framework technology. How can you get a promotion and raise and boost your resume? Spring Cloud and Dubbo need to be studied separately. No time? No energy? Two frames to learn? Spring Cloud Alibaba, on the other hand, only needs you to learn one to have two microservices governance framework technologies. Why not? Come on! In SAO ape

In the last article, we showed that Gateway’s routing function is similar to zuul’s routing and forwarding. Today I’m going to focus on assertion mechanisms.

Built-in assertion factory

This section describes how the Spring Cloud Gateway matches routes as part of the Spring WebFlux HandlerMapping infrastructure. The Spring Cloud Gateway includes a number of built-in Route Predicate factories. All of these assertions match the different attributes of the HTTP request. Multiple Route Predicate factories can be combined or logically combined

You can see the way Gateway provides so many rich assertions.

  • Time-controlled, for example, we can think of seckill scenarios.
  • IP we can think of canary test
  • Weights we can use grayscale and so on

The specific use should refer to the business scenario to choose the business scenario that is more suitable for us.

Gateway filters are classified into global filters and personalized filters

Gateway already provides us with very rich filters

  • AddRequestHeader GatewayFilter Factory takes name and value parameters.
This adds the X-request-foo :Bar header to the headers of all downstream requests that match the Request.Copy the code
        spring:
            cloud:
                gateway:
                    routes:
                    - id: add_request_header_route
                        uri: https://example.org
                        filters:
                        - AddRequestHeader=X-Request-Foo, BarCopy the code
The AddRequestHeader knows the URI variable used to match the path or host. The URI variable can be used for this value and will be extended at run time.Copy the code
        spring:
            cloud:
                gateway:
                    routes:
                    - id: add_request_header_route
                        uri: https://example.org
                        predicates:
                        - Path=/foo/{segment}
                        filters:
                        - AddRequestHeader=X-Request-Foo, Bar-{segment}Copy the code

-AddResponseHeader GatewayFilter The factory takes the name and value parameters.

    spring:
        cloud:
            gateway:
                routes:
                - id: add_request_parameter_route
                    uri: https://example.org
                    filters:
                    - AddRequestParameter=foo, barCopy the code

This adds foo=bar to the query string of all downstream requests that match the request.

AddRequestParameter knows the URI variable used to match the path or host. The URI variable can be used for this value and will be extended at run time.

    spring:
        cloud:
            gateway:
                routes:
                - id: add_request_parameter_route
                    uri: https://example.org
                    predicates:
                    - Host: {segment}.myhost.org
                    filters:
                    - AddRequestParameter=foo, bar-{segment}Copy the code
  • AddResponseHeader GatewayFilter Factory takes name and value parameters.
     spring:
            cloud:
                gateway:
                    routes:
                    - id: add_response_header_route
                        uri: https://example.org
                        filters:
                        - AddResponseHeader=X-Response-Foo, BarCopy the code
This adds the X-Response-foo :Bar header to the headers of all downstream responses that match requests.Copy the code
The AddResponseHeader knows the URI variable used to match the path or host. The URI variable can be used for this value and will be extended at run time. spring: cloud: gateway: routes: - id: add_response_header_route uri: https://example.org predicates: - Host: {segment}.myhost.org filters: - AddResponseHeader=foo, bar-{segment}Copy the code
  • The DedupeResponseHeader GatewayFilter factory takes a name parameter and an optional strategy parameter. Name can contain a list of title names, separated by Spaces.

    spring:

    cloud:

    gateway:

    routes:
    • id: deduperesponseheader_route

      uri: https://example.org

      filters:
      • DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
If both the gateway CORS logic and downstream logic add duplicate values to the access-Control-allow-Credentials and Access-Control-allow-Origin response headers, this will remove them.Copy the code
The DedupeResponseHeader filter also accepts an optional strategy argument. Acceptable values are RETAIN_FIRST (default) RETAIN_LAST, and RETAIN_UNIQUECopy the code
  • Hystrix is a Netflix library for implementing circuit breaker mode. Hystrix GatewayFilters allow you to introduce circuit breakers into gateway routing, protect your service from cascading failures, and allow you to provide backup response in case of downstream failures to enable Hystrix GatewayFilters in your project, Spring-cloud-starter-netflix-hystrix adds dependencies from Spring Cloud Netflix.
Hystrix GatewayFilter factory requires a name parameter, which is the name HystrixCommand. spring: cloud: gateway: routes: - id: hystrix_route uri: https://example.org filters: - Hystrix=myCommandNameCopy the code

This wraps the rest of the filters in myCommandName with the command name in HystrixCommand.

The Hystrix filter can also accept an optional fallbackUri parameter. Currently, only forward: supports the plan URI. If backup is invoked, the request is forwarded to the controller that matches the URI.

        spring:
            cloud:
                gateway:
                    routes:
                    - id: hystrix_route
                        uri: lb://backing-service:8088
                        predicates:
                        - Path=/consumingserviceendpoint
                        filters:
                        - name: Hystrix
                            args:
                                name: fallbackcmd
                                fallbackUri: forward:/incaseoffailureusethis
                        - RewritePath=/consumingserviceendpoint, /backingserviceendpoint
Copy the code

/ incaseoffailureUseThis When Hystrix backup is called, it is forwarded to the URI. Note that this example also demonstrates (optionally) Spring Cloud Netflix Ribbon load balancing via the prefix on the LB target URI.

The primary scenario is for use with internal controllers or handlers in fallbackUri gateway applications. However, requests can also be rerouted to controllers or handlers in external applications, as follows:

    
        spring:
            cloud:
                gateway:
                    routes:
                    - id: ingredients
                        uri: lb://ingredients
                        predicates:
                        - Path=//ingredients/**
                        filters:
                        - name: Hystrix
                            args:
                                name: fetchIngredients
                                fallbackUri: forward:/fallback
                    - id: ingredients-fallback
                        uri: http://localhost:9994
                        predicates:
                        - Path=/fallbackCopy the code

In this example, there is no endpoint or handler in the Fallback Gateway application, but one endpoint or handler in the other application, register localhost:9994 below.

The Hystrix gateway filter also provides Throwable to cause the request if the request is forwarded to the backup. . It has ServerWebExchange as ServerWebExchangeUtils HYSTRIXEXECUTIONEXCEPTION_ATTR attribute is added to, can be used when processing a backup in the gateway application.

For external controller/handler scenarios, you can add headers with exception details. You can find more information about it in the FallbackHeaders GatewayFilter Factory section.

Hystrix Settings (such as timeouts) can be configured using global defaults or on a routing-by-route basis using the application properties described on the Hystrix Wiki.

To set a 5-second timeout for the example route above, use the following configuration:

    hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds: 5000
Copy the code
  • The FallbackHeaders factory allows you to add the hedgehog to the header of the forward request to perform the exception details of the fallbackUri in the following cases in external applications

    spring:

    cloud:

    gateway:

    routes:
    • id: ingredients

      uri: lb://ingredients

      predicates:
      • Path=//ingredients/**

        filters:
      • name: Hystrix

        args:

        name: fetchIngredients

        fallbackUri: forward:/fallback
    • id: ingredients-fallback

      uri: http://localhost:9994

      predicates:
      • Path=/fallback

        filters:
      • name: FallbackHeaders

        args:

        executionExceptionTypeHeaderName: Test-Header
In this example, HystrixCommand after an execution exception occurs at run time, and the request is forwarded to the endpoint or handler localhost:9994 in the application running on fallback. The header with the exception type, message and -if available- root cause exception type and message will be added to the request by the FallbackHeaders filter.Copy the code

You can override header names in the configuration by setting the values of the parameters listed below and their default values:

- executionExceptionTypeHeaderName (" Execution - the Exception - Type ")Copy the code
- executionExceptionMessageHeaderName (" Execution - the Exception - the Message ")Copy the code
- rootCauseExceptionTypeHeaderName (" Root Cause - Exception - Type ")Copy the code
- rootCauseExceptionMessageHeaderName (" Root Cause - the Exception - the Message ")Copy the code

You can find more information about how Hystrix works with the Gateway in the Hystrix GatewayFilter Factory section.

  • MapRequestHeader GatewayFilter factory uses ‘fromHeader’ and ‘toHeader’ parameters. It creates a new named header (toHeader) and extracts the value from the existing named header (fromHeader) from the incoming HTTP request. If the input header does not exist, the filter does not work. If the new named header already exists, its value is augmented with the new value.
        spring:
            cloud:
                gateway:
                    routes:
                    - id: map_request_header_route
                        uri: https://example.org
                        filters:
                        - MapRequestHeader=Bar, X-Request-FooCopy the code

This adds the X-Request-foo: header to the downstream Request header, which contains the updated value from the incoming HTTP Request Bar header.

  • PrefixPath GatewayFilter Factory uses a single prefix parameter.

    spring:

    cloud:

    gateway:

    routes:
    • id: prefixpath_route

      uri: https://example.org

      filters:
      • PrefixPath=/mypath

This prefixes /mypath to all paths matching requests. Therefore, the request for /hello will be sent to /mypath/hello.

  • PreserveHostHeader GatewayFilter Factory has no parameters. This filter sets the request property, which the routing filter checks to determine whether the original host header should be sent instead of the one determined by the HTTP client.
spring: cloud: gateway: routes: - id: preserve_host_route uri: https://example.org filters: - PreserveHostHeader - RequestRateLimiter GatewayFilter Factory Uses a RateLimiter implementation to determine whether the current request is allowed to continue. If not, HTTP 429-Too Many Requests returns the status (default). This filter takes an optional keyResolver parameter and a rate limiter specific parameter.Copy the code
  • Redis RateLimiter GatewayFilter factory Redis implements work based on Stripe. It needs to use the spring-boot-starter-data-redis-reactivespring boot initiator.
  • The RedirectTo GatewayFilter factory uses the status and URL parameters. The status should be 300 series redirect HTTP code, such as 301. The URL should be a valid URL. This will be the value of the Location header
  • RemoveHopByHopHeadersFilter GatewayFilter factory is removed from the forward request headers. The default list of deleted headers is from the IETF.
  • The RemoveRequestHeader GatewayFilter factory takes a name parameter. It is the name of the title to be deleted.
  • The RemoveResponseHeader GatewayFilter factory takes a name parameter. It is the name of the title to be deleted.
  • RemoveRequestParameter GatewayFilter The factory takes a name parameter. It is the name of the query parameter to delete.
  • The RewritePath GatewayFilter factory uses the path regexp parameter and replacement parameter. This provides a flexible way to override the request path using Java regular expressions.
  • RewriteLocationResponseHeader GatewayFilter factory Location usually changes the value of the response headers to get rid of the backend specific details. This requires stripVersionMode, locationHeaderName, hostValue, and protocolsRegex parameters.
  • The RewriteResponseHeader GatewayFilter factory requires name, regexp, and replacement parameters. It uses Java regular expressions to override response header values in a flexible manner.
  • SaveSession GatewayFilter Factory forces the WebSession::save operation before forwarding the call downstream. This is especially useful when using something like Spring Session with lazy data stores, and you need to ensure that Session state is saved before forwarding calls.
  • SetPath GatewayFilter The factory uses the path template parameter. It provides a simple way to manipulate the request path by allowing template segments for the path. This uses uri templates from the Spring Framework. Multiple matching segments are allowed.
  • SetRequestHeader GatewayFilter Factory uses name and value parameters.
  • SetResponseHeader GatewayFilter The factory takes the name and value parameters
  • SetStatus GatewayFilter The factory uses a single status parameter. It must be a valid Spring HttpStatus. It can be the integer value 404 or the string representation of an enumeration NOT_FOUND
  • The StripPrefix GatewayFilter factory takes one parameter, parts. The parts parameter indicates the number of parts in the path to be stripped from the request before it is sent downstream
  • Retry GatewayFilter factory
  • RequestSize GatewayFilter Factory the RequestSize GatewayFilter Factory can limit the RequestSize from reaching the downstream service if the RequestSize is greater than the allowed limit. The filter takes the RequestSize parameter as the allowable size limit (in bytes) for the request
  • This filter is considered BETA and may be changed by the API in the future. This filter can be used to modify the request body before the gateway sends it downstream.
  • The default filter If you want to add the filter and applied to all routing, you can use spring. Cloud. Gateway. The default – filters. This property takes a list of filters
  • GlobalFilter the GlobalFilter interface has the same signature GatewayFilter. These are special filters that apply conditionally to all routes. (This interface and usage may change in future milestones).
  • A combination of global filter and GatewayFilter ordering

The Spring Cloud Gateway provides too many built-in filters. Not here to introduce one by one can see the official documentation to understand learning

Gateway Official Documentation

https://cloud.spring.io/spring-cloud-gateway/reference/html/

Next, the GlobalFilter interface.

  • The GlobalFilter and GatewayFilter #filter(ServerWebExchange, GatewayFilterChain) methods have the same signature.
  • GlobalFilter applies to all routes;
  • Some adjustments may be made in future milestone releases;

You can look at the global filters implemented by default, except for the AuthorizeFilter filter

Specific inside the role, in fact, the above has a simple description is not retelling. Interested students can have a look inside the implementation, are the use of filters to do forwarding or some of the traffic request modification, authentication, and other operations

You can use the Actuator module monitoring to query the GlobalFilter implementation

1. Pom imports spring-boot-starter-actuator. The import operation was done directly in the parent POM. Not reintroduce

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>Copy the code

2. Enable the monitoring management endpoint in the bootstrap.yml configuration file


management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: ALWAYSCopy the code

3, browser requests at http://localhost:9000/actuator/gateway/globalfilters

{
org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter@4b957db0: -2147482648,
org.springframework.cloud.gateway.filter.WebsocketRoutingFilter@273fa9e: 2147483646,
com.xian.cloud.filter.AuthorizeFilter@4b03cbad: 0,
org.springframework.cloud.gateway.filter.ForwardRoutingFilter@8840c98: 2147483647,
org.springframework.cloud.gateway.filter.NettyRoutingFilter@5c313224: 2147483647,
org.springframework.cloud.gateway.filter.NettyWriteResponseFilter@1e1e837d: -1,
org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter@5d71b500: 10000,
org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@5b29ab61: 10100,
org.springframework.cloud.gateway.filter.GatewayMetricsFilter@527a8665: -2147473648,
org.springframework.cloud.gateway.filter.ForwardPathFilter@626b639e: 0
}Copy the code

Look at the implementation classes. Both implement the GlobalFilter and Ordered interfaces to implement their own global filters

Create AuthorizeFilter

package com.xian.cloud.filter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.http.HttpHeaders; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; /** * <Description> ** @author [email protected] * @version 1.0 * @createdate 2019/11/04 18:06 */ @component @slf4j public class AuthorizeFilter implements GlobalFilter, Ordered { private static final String AUTHORIZE_TOKEN = "Authorization"; private static final String AUTHORIZE_UID = "uid"; @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); HttpHeaders headers = request.getHeaders(); ServerHttpRequest.Builder mutate = request.mutate(); String token = headers.getFirst( AUTHORIZE_TOKEN ); String uid = headers.getFirst( AUTHORIZE_UID ); String method = request.getMethodValue(); Log.info ("AuthorizeFilter Token Global filter Token :{},uid:{}",token,uid); if (token == null) { token = request.getQueryParams().getFirst( AUTHORIZE_TOKEN ); } if(stringutils. isNotBlank(token)){//TODO permission validation} return chain.filter(exchange); } @Override public int getOrder() { return 0; }}Copy the code

Then start the service.

The curl http://localhost:9000/client/client/test log printing

[the 2019-11-05 19:30:52. 802] [INFO] com. Xian. Cloud. Filter. AuthorizeFilter - AuthorizeFilter token global filter token:null,uid:nullCopy the code

In the next article we will cover custom filters that correspond to downstream services

Excerpt from the spring Cloud official documentation

Sample code address

Nacos address http://47.99.209.72:8848/nacos server

Address of Spring Cloud Alibaba

Introduction to Spring Cloud Alibaba

Spring Cloud Alibaba (Establishment of NACOS Registry)

Spring Cloud Alibaba uses the NACOS registry

Spring Cloud Alibaba NacOS configuration center use

Spring Cloud Gateway services

Spring Cloud Zuul Gateway Service one

Spring Cloud Gateway service Zuul ii

Spring Cloud Gateway service Zuul three dynamic routing

Spring Cloud Alibaba Gateway Sentinel Zuul quad-current limited fuse

Spring Cloud Gateway Gateway service 1

How can you like to share this public number.

Copyright notice: This article is originally published BY the blogger. It follows the COPYRIGHT agreement CC 4.0 BY-SA. Please attach the link of the original source and this statement. Please attach the qr code of the public account