Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand assertions and filters in Spring Cloud gateway Gateway Services

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to understand assertions and filters in Spring Cloud gateway Gateway Services". In daily operations, I believe many people have doubts about how to understand assertions and filters in Spring Cloud gateway Gateway Services. I have consulted all kinds of materials and sorted out simple and useful operation methods. I hope it will be helpful for you to answer the doubts about "how to understand assertions and filters in Spring Cloud gateway Gateway Services". Next, please follow the editor to study!

The built-in assertion factory describes that Spring Cloud Gateway matches routes as part of the Spring WebFlux HandlerMapping infrastructure. Spring Cloud Gateway includes many built-in Route Predicate factories. All these assertions match the different properties of the HTTP request. Multiple Route Predicate factories can be merged or logically merged

You can see that gateway provides so many assertions in such a way.

For example, if the time is controlled, we can think of the second kill scene.

Ip, we can think of the canary test.

Weight we can use grayscale and other scenarios.

For specific use, we have to refer to the business scenario to choose a business scenario that is more suitable for us.

Gateway filter is divided into global filter and personalized filter.

Gateway has provided us with a very rich range of filters.

The 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. Spring: cloud: gateway: routes:-id: add_request_header_route uri: https://example.org filters:-AddRequestHeader=X-Request-Foo, Bar 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. Spring: cloud: gateway: routes:-id: add_request_header_route uri: https://example.org predicates:-Path=/foo/ {segment} Filters:-AddRequestHeader=X-Request-Foo Bar- {segment}

-the AddResponseHeader GatewayFilter factory takes name and value parameters.

Spring: cloud: gateway: routes:-id: add_request_parameter_route uri: https://example.org filters:-AddRequestParameter=foo, bar

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}

The 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, Bar

This adds the X-Response-Foo:Bar header to the headers of all downstream responses that match the request.

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}

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: dedupe_response_header_route uri: https://example.org filters:-DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin

If both the gateway CORS logic and the downstream logic add duplicate value Access-Control-Allow-Credentials and Access-Control-Allow-Origin response headers, this removes them.

The DedupeResponseHeader filter also accepts the optional strategy parameter. Acceptable values are RETAIN_FIRST (default) RETAIN_LAST, and RETAIN_UNIQUE

Hystrix is a library of Netflix that implements circuit breaker mode. Hystrix GatewayFilter allows you to introduce circuit breakers into gateway routing, protect your services from cascading failures, and allow you to provide backup responses in the event of downstream failures to enable Hystrix GatewayFilters in the project, ask spring-cloud-starter-netflix-hystrix to add dependencies from Spring Cloud Netflix.

The Hystrix GatewayFilter factory requires a name parameter, which is the name of HystrixCommand. Spring: cloud: gateway: routes:-id: hystrix_route uri: https://example.org filters:-Hystrix=myCommandName

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

The Hystrix filter can also accept the optional fallbackUri parameter. Currently, only forward: the planned URI is supported. If fallback 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

When / incaseoffailureusethis invokes Hystrix fallback, it will be forwarded to URI. Note that this example also demonstrates (optional) Spring Cloud Netflix Ribbon load balancing with a prefix on the lb target URI.

The main solution is to use internal controllers or handlers in fallbackUri gateway applications. However, you can also reroute the request to a controller or handler in the external application, 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=/fallback

In this example, there is no endpoint or handler in the fallback gateway application, but there is an endpoint or handler in another application that registers localhost:9994 under.

If the request is forwarded to the backup, the Hystrix gateway filter also provides Throwable to cause the request. It has been added to the ServerWebExchange as a ServerWebExchangeUtils.HYSTRIX_EXECUTION_EXCEPTION_ATTR attribute and can be used when handling fallbacks in gateway applications.

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 default values or on a route-by-route basis using the application properties described on Hystrix Wiki.

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

Hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds: 5000

The FallbackHeaders factory allows you to add the details of the hedgehog execution exception to the header forwarded to the request fallbackUri in the external application 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, after an execution exception occurs at run time, the HystrixCommand, the request is forwarded to the endpoint or handler localhost:9994 in the application running on fallback. With exception types, messages and-if available- root cause exception types and message headers are added to the request by the FallbackHeaders filter.

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

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

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

The MapRequestHeader GatewayFilter factory takes the '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 expanded with the new value.

Spring: cloud: gateway: routes:-id: map_request_header_route uri: https://example.org filters:-MapRequestHeader=Bar, X-Request-Foo

This adds the X-Request-Foo: header to the header of the downstream request, which contains the update value from the incoming HTTP request Bar header.

The PrefixPath GatewayFilter factory takes a single prefix parameter. Spring: cloud: gateway: routes:-id: prefixpath_route uri: https://example.org filters:-PrefixPath=/mypath

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

The PreserveHostHeader GatewayFilter factory has no parameters. This filter sets the request property, which is checked by the route filter 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 an 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.

The Redis RateLimiter GatewayFilter factory redis implementation is based on the work done by Stripe. It requires the use of a spring-boot-starter-data-redis-reactiveSpring Boot initiator.

The RedirectTo GatewayFilter factory uses status and url parameters. The status should be a 300 series redirect http code, such as 301. URL should be a valid URL. This will be the value of the Location title

The RemoveHopByHopHeadersFilter GatewayFilter factory removes the header from the forwarded request. The default list of deleted headers comes from IETF.

The RemoveRequestHeader GatewayFilter factory takes a name parameter. It is the name of the title to delete.

The RemoveResponseHeader GatewayFilter factory takes a name parameter. It is the name of the title to delete.

The RemoveRequestParameter GatewayFilter factory takes a name parameter. It is the name of the query parameter to delete.

The RewritePath GatewayFilter factory takes the path regexp parameter and the replacement parameter. This uses Java regular expressions to provide a flexible way to rewrite the request path.

The RewriteLocationResponseHeader GatewayFilter factory Location usually modifies the value of the response header to get rid of the back-end specific details. This requires the stripVersionMode,locationHeaderName,hostValue, and protocolsRegex parameters.

The RewriteResponseHeader GatewayFilter factory requires name,regexp and replacement parameters. It uses Java regular expressions to rewrite response header values in a flexible manner.

SaveSession GatewayFilter Factory enforces a WebSession::save operation before forwarding the call downstream. This is especially useful when using things like Spring Session with lazy data stores, and you need to make sure that session state is saved before forwarding calls.

The SetPath GatewayFilter factory takes the path template parameter. By allowing the template segment of the path, it provides an easy way to manipulate the request path. This uses the uri template in Spring Framework. Multiple matching segments are allowed.

The SetRequestHeader GatewayFilter factory uses name and value parameters.

SetResponseHeader GatewayFilter factory uses name and value parameters

The SetStatus GatewayFilter factory takes a single status parameter. It must be a valid Spring HttpStatus. It can be an integer value of 404 or a string representation of the enumeration NOT_FOUND

The StripPrefix GatewayFilter factory takes one parameter, parts. This parts parameter indicates the number of parts in the path to be stripped from the request before sending the request downstream

Retry the GatewayFilter factory

RequestSize GatewayFilter factory RequestSize GatewayFilter Factory can restrict requests to downstream services when the request size is larger than the allowed limit. The filter takes the RequestSize parameter as the allowable size limit for the request (in bytes

Modify request body GatewayFilter factory this filter is thought to be that BETA,API may change in the future this filter can be used to modify the request body before the gateway sends the request body downstream.

Default filter if you want to add a filter and apply it to all routes, you can use spring.cloud.gateway.default-filters. This attribute uses a filter list

Global filter the GlobalFilter interface has the same signature GatewayFilter. These are special filters that are conditionally applied to all routes. This interface and usage may change in future milestones.

Combined ordering of global filter and GatewayFilter

Because spring cloud gateway provides too many built-in filters. If you don't introduce them here, you can check the official documents to learn about them.

Gateway official documentation

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

Next, let's talk about the global filter GlobalFilter interface.

The # filter (ServerWebExchange, GatewayFilterChain) method signatures of GlobalFilter and GatewayFilter are identical

GlobalFilter will act on all routes

Some adjustments may be made in future milestone releases

You can take a look at the default implementation of the global filter, except for the AuthorizeFilter filter is the default filter

Specific inside the role, in fact, the above already has a simple description is not repeated. Interested students can take a look at the implementation, which uses filters to forward or modify traffic requests, authentication, and other operations.

You can monitor and query GlobalFilter implementation classes through the actuator module

1. Pom introduces spring-boot-starter-actuator. Because the introduction operation was carried out directly in parent pom before. Do not re-introduce

Org.springframework.boot spring-boot-starter-actuator

2. Open the monitoring and management endpoint in the configuration file bootstrap.yml

Management: endpoints: web: exposure: include: "*" endpoint: health: show-details: ALWAYS

3. Request browser http://localhost:9000/actuator/gateway/globalfilters

{org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter@4b957db0:-2147482648 reorg.springframework.cloud.gateway.filter.WebsocketRoutingFilterkeeper 273fa9e: 2147483646 com.xian.cloud.filter.AuthorizeFiltermakers 4b03cbad: 0reorg.springframework.cloud.gateway.filter.ForwardRoutingFiltermakers 8840c98: 214748364org.springframework.cloud.gateway.filter.NettyRoutingFilterframes 5c313224: 214748364org.springframework.cloud.gatewaywork.cloud.gateway.NetWriteponResterFilter1e137d:-1gmentor.springfrawork.cloud.gateway.filter.R147483647org.springframework.netWriteResterFilter1e137d Org.springframework.cloud.gateway.filter.GatewayMetricsFilter@527a8665:-2147473648 Magi org.springframework.cloud.gateway.filter.ForwardPathFilter626b639e: 0}

Observe these implementation classes. They all implement 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 / * @ author xianliru@100tal.com * @ version 1.0 * @ createDate 18:06 on 2019-11-04 * / @ Component@Slf4jpublic class AuthorizeFilter implements GlobalFilter, Ordered {private static final String AUTHORIZE_TOKEN = "Authorization"; private static final String AUTHORIZE_UID = "uid"; @ Override public Mono 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 verification} return chain.filter (exchange);} @ Override public int getOrder () {return 0;}}

Then start the service.

Curl http://localhost:9000/client/client/test log printing

[2019-11-05 19 AuthorizeFilter token 30 AuthorizeFilter token 52.802] [INFO] Global filter token:null,uid:null-this is the end of the study on "how to understand assertions and filters in Spring Cloud gateway Gateway Services". I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report