SpringCloud 2.x学习笔记:15、Spring Cloud Gateway之Filter过滤器(Greenwich版本)
程序员文章站
2022-06-13 14:01:00
...
1、AddRequestHeader过滤器
server:
port: 7013
---
spring:
cloud:
gateway:
routes:
- id: add_request_header_route
uri: http://httpbin.org
filters:
- AddRequestHeader=X-Request-Flag, HelloWorld
predicates:
- After=2019-06-20T00:00:00+08:00[Asia/Shanghai]
profiles: add_request_header_route
http://localhost:7013/get
AddRequestHeaderGatewayFilterFactory的源码
package org.springframework.cloud.gateway.filter.factory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
/**
* @author Spencer Gibb
*/
public class AddRequestHeaderGatewayFilterFactory
extends AbstractNameValueGatewayFilterFactory {
@Override
public GatewayFilter apply(NameValueConfig config) {
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest().mutate()
.header(config.getName(), config.getValue()).build();
return chain.filter(exchange.mutate().request(request).build());
};
}
}
从代码可知道,由当前的ServerHttpRequest创建新 ServerHttpRequest ,并在新的ServerHttpRequest加一个请求头,然后创建新的 ServerWebExchange ,提交过滤器链继续过滤。
2、AddRequestHeader过滤器
---
spring:
cloud:
gateway:
routes:
- id: add_response_header_route
uri: http://httpbin.org:80/get
filters:
- AddResponseHeader=X-Response-Flag, Hadron
predicates:
- After=2019-06-20T00:00:00+08:00[Asia/Shanghai]
profiles: add_response_header_route
C:\Windows\System32>curl -I localhost:7013
HTTP/1.1 200 OK
X-Response-Flag: Hadron
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Content-Type: text/html; charset=utf-8
Date: Fri, 21 Jun 2019 09:01:14 GMT
Referrer-Policy: no-referrer-when-downgrade
Server: nginx
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Content-Length: 0
3、RewritePath 过滤器
---
spring:
cloud:
gateway:
routes:
- id: rewritepath_route
uri: https://blog.csdn.net/chengyuqiang
predicates:
- Path=/foo/**
filters:
- RewritePath=/foo/(?<segment>.*), /$\{segment}
profiles: rewritepath_route
RewritePath 过滤器将/foo/(?.*)重写为{segment},然后转发到https://blog.csdn.net。
比如请求http://localhost:7013/foo/chengyuqiang
,RewritePath 过滤器将/foo/chengyuqiang
重写为chengyuqiang
,然后转发到https://blog.csdn.net
,这样路径就是https://blog.csdn.net/chengyuqiang
http://localhost:7013/foo/chengyuqiang
4、
上一篇: C/C++算法设计实验报告(源代码)
下一篇: 动态库静态库的链接过程