文档章节

聊聊spring cloud gateway的RemoveHopByHopHeadersFilter

go4it
 go4it
发布于 05/30 22:45
字数 635
阅读 78
收藏 2

本文主要研究一下spring cloud gateway的RemoveHopByHopHeadersFilter

GatewayAutoConfiguration

spring-cloud-gateway-core-2.0.0.RC1-sources.jar!/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.java

@Configuration
@ConditionalOnProperty(name = "spring.cloud.gateway.enabled", matchIfMissing = true)
@EnableConfigurationProperties
@AutoConfigureBefore(HttpHandlerAutoConfiguration.class)
@AutoConfigureAfter({GatewayLoadBalancerClientAutoConfiguration.class, GatewayClassPathWarningAutoConfiguration.class})
@ConditionalOnClass(DispatcherHandler.class)
public class GatewayAutoConfiguration {
    //......
    @Bean
	public RemoveHopByHopHeadersFilter removeHopByHopHeadersFilter() {
		return new RemoveHopByHopHeadersFilter();
	}
    //......
}

可以看到这里自动new了一个RemoveHopByHopHeadersFilter

RemoveHopByHopHeadersFilter

spring-cloud-gateway-core-2.0.0.RC1-sources.jar!/org/springframework/cloud/gateway/filter/headers/RemoveHopByHopHeadersFilter.java

@ConfigurationProperties("spring.cloud.gateway.filter.remove-hop-by-hop")
public class RemoveHopByHopHeadersFilter implements HttpHeadersFilter, Ordered {

	public static final Set<String> HEADERS_REMOVED_ON_REQUEST =
			new HashSet<>(Arrays.asList(
					"connection",
					"keep-alive",
					"transfer-encoding",
					"te",
					"trailer",
					"proxy-authorization",
					"proxy-authenticate",
					"x-application-context",
					"upgrade"
					// these two are not listed in https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-14#section-7.1.3
					//"proxy-connection",
					// "content-length",
					));

	private int order = Ordered.LOWEST_PRECEDENCE;

	private Set<String> headers = HEADERS_REMOVED_ON_REQUEST;

	public Set<String> getHeaders() {
		return headers;
	}

	public void setHeaders(Set<String> headers) {
		this.headers = headers;
	}

	@Override
	public int getOrder() {
		return order;
	}

	public void setOrder(int order) {
		this.order = order;
	}

	@Override
	public HttpHeaders filter(HttpHeaders input, ServerWebExchange exchange) {
		HttpHeaders filtered = new HttpHeaders();
		
		input.entrySet().stream()
				.filter(entry -> !this.headers.contains(entry.getKey().toLowerCase()))
				.forEach(entry -> filtered.addAll(entry.getKey(), entry.getValue()));

		return filtered;
	}

	@Override 
	public boolean supports(Type type) {
		return type.equals(Type.REQUEST) ||
				type.equals(Type.RESPONSE);
	}
}

可以看到这个filter是移除request或response中指定的header,默认移除的header包括"connection","keep-alive", "transfer-encoding","te","trailer","proxy-authorization","proxy-authenticate","x-application-context","upgrade"。 也可以自己在配置文件指定要移除的header

配置

spring-cloud-gateway-core-2.0.0.RC1.jar!/META-INF/spring-configuration-metadata.json

    {
      "sourceType": "org.springframework.cloud.gateway.filter.headers.RemoveHopByHopHeadersFilter",
      "name": "spring.cloud.gateway.filter.remove-hop-by-hop.headers",
      "type": "java.util.Set<java.lang.String>"
    },
    {
      "sourceType": "org.springframework.cloud.gateway.filter.headers.RemoveHopByHopHeadersFilter",
      "name": "spring.cloud.gateway.filter.remove-hop-by-hop.order",
      "type": "java.lang.Integer"
    }

可以看到,有个order属性用来指定该filter的优先级,默认是Ordered.LOWEST_PRECEDENCE 还有另外一个属性headers,用来指定要移除的header

实例

spring:
  cloud:
    gateway:
      filter:
        remove-hop-by-hop:
          headers:
            - x-route
            - x-auth-id

使用

spring-cloud-gateway-core-2.0.0.RC1-sources.jar!/org/springframework/cloud/gateway/filter/NettyRoutingFilter.java

public class NettyRoutingFilter implements GlobalFilter, Ordered {

	private final HttpClient httpClient;
	private final ObjectProvider<List<HttpHeadersFilter>> headersFilters;

	public NettyRoutingFilter(HttpClient httpClient,
			ObjectProvider<List<HttpHeadersFilter>> headersFilters) {
		this.httpClient = httpClient;
		this.headersFilters = headersFilters;
	}

	@Override
	public int getOrder() {
		return Ordered.LOWEST_PRECEDENCE;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);

		String scheme = requestUrl.getScheme();
		if (isAlreadyRouted(exchange) || (!"http".equals(scheme) && !"https".equals(scheme))) {
			return chain.filter(exchange);
		}
		setAlreadyRouted(exchange);

		ServerHttpRequest request = exchange.getRequest();

		final HttpMethod method = HttpMethod.valueOf(request.getMethod().toString());
		final String url = requestUrl.toString();

		HttpHeaders filtered = filterRequest(this.headersFilters.getIfAvailable(),
				exchange);

		final DefaultHttpHeaders httpHeaders = new DefaultHttpHeaders();
		filtered.forEach(httpHeaders::set);

		String transferEncoding = request.getHeaders().getFirst(HttpHeaders.TRANSFER_ENCODING);
		boolean chunkedTransfer = "chunked".equalsIgnoreCase(transferEncoding);

		boolean preserveHost = exchange.getAttributeOrDefault(PRESERVE_HOST_HEADER_ATTRIBUTE, false);

		return this.httpClient.request(method, url, req -> {
			final HttpClientRequest proxyRequest = req.options(NettyPipeline.SendOptions::flushOnEach)
					.headers(httpHeaders)
					.chunkedTransfer(chunkedTransfer)
					.failOnServerError(false)
					.failOnClientError(false);

			if (preserveHost) {
				String host = request.getHeaders().getFirst(HttpHeaders.HOST);
				proxyRequest.header(HttpHeaders.HOST, host);
			}

			return proxyRequest.sendHeaders() //I shouldn't need this
					.send(request.getBody().map(dataBuffer ->
							((NettyDataBuffer)dataBuffer).getNativeBuffer()));
		}).doOnNext(res -> {
			ServerHttpResponse response = exchange.getResponse();
			// put headers and status so filters can modify the response
			HttpHeaders headers = new HttpHeaders();
			
			res.responseHeaders().forEach(entry -> headers.add(entry.getKey(), entry.getValue()));

			HttpHeaders filteredResponseHeaders = HttpHeadersFilter.filter(
					this.headersFilters.getIfAvailable(), headers, exchange, Type.RESPONSE);
			
			response.getHeaders().putAll(filteredResponseHeaders);
			HttpStatus status = HttpStatus.resolve(res.status().code());
			if (status != null) {
				response.setStatusCode(status);
			} else if (response instanceof AbstractServerHttpResponse) {
				// https://jira.spring.io/browse/SPR-16748
				((AbstractServerHttpResponse) response).setStatusCodeValue(res.status().code());
			} else {
				throw new IllegalStateException("Unable to set status code on response: " +res.status().code()+", "+response.getClass());
			}

			// Defer committing the response until all route filters have run
			// Put client response as ServerWebExchange attribute and write response later NettyWriteResponseFilter
			exchange.getAttributes().put(CLIENT_RESPONSE_ATTR, res);
		}).then(chain.filter(exchange));
	}
}

这里头对于request,调用的是

		HttpHeaders filtered = filterRequest(this.headersFilters.getIfAvailable(),
				exchange);

对于response调用的是

			HttpHeaders filteredResponseHeaders = HttpHeadersFilter.filter(
					this.headersFilters.getIfAvailable(), headers, exchange, Type.RESPONSE);

小结

RemoveHopByHopHeadersFilter可以用来移除指定的header,其作用于request及response。

doc

© 著作权归作者所有

共有 人打赏支持
go4it
粉丝 70
博文 791
码字总数 628416
作品 0
深圳
私信 提问
聊聊spring cloud gateway的GatewayFilter

序 本文主要研究一下spring cloud gateway的GatewayFilter GatewayFilter spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/GatewayFilter.jav......

go4it
06/09
0
0
聊聊spring.cloud.gateway.default-filters

序 本文主要研究下spring.cloud.gateway.default-filters 配置 default-filters,配置的是FilterDefinition对象 FilterDefinition spring-cloud-gateway-core-2.0.0.RC1-sources.jar!/org/sp......

go4it
06/01
0
0
聊聊spring cloud的RequestHeaderToRequestUri

序 本文主要研究一下spring cloud的RequestHeaderToRequestUriGatewayFilter GatewayAutoConfiguration spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gate......

go4it
06/16
0
0
聊聊spring cloud gateway的RedirectToGatewayFilter

序 本文主要研究下spring cloud gateway的RedirectToGatewayFilter GatewayAutoConfiguration spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/confi......

go4it
06/13
0
0
聊聊spring cloud gateway的SetStatusGatewayFilter

序 本文主要研究下spring cloud gateway的SetStatusGatewayFilter GatewayAutoConfiguration spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/config......

go4it
06/15
0
0

没有更多内容

加载失败,请刷新页面

加载更多

程序员,你焦虑吗?

前言 我很焦虑,请问程序员们,你焦虑吗? 我是一名年过35的北漂程序员,我身边的朋友大多也是程序员。我总感觉到30岁以上的程序员充满了焦虑。“华为清退35岁以上老员工”、“中兴程序员坠楼...

Ala6
22分钟前
1
0
RabbitMQ+PHP 教程一(Hello World)用yii2测试通过

介绍 RabbitMQ是一个消息代理器:它接受和转发消息。你可以把它当作一个邮局:当你把邮件放在信箱里时,你可以肯定邮差先生最终会把邮件送到你的收件人那里。在这个比喻中,RabbitMQ就是这里...

hansonwong
28分钟前
0
0
Netty原理分析往这边看!

Netty是一个高性能、异步事件驱动的NIO框架,它提供了对TCP、UDP和文件传输的支持,作为一个异步NIO框架,Netty的所有IO操作都是异步非阻塞的,通过Future-Listener机制,用户可以方便的主动...

Java干货分享
32分钟前
2
0
在Scala中构建Web API的4大框架

Scala是一种强大的语言,很快就成为许多开发人员的最爱。然而,语言只是一个起点-并非每个函数都将由语言核心覆盖。Scala还创建了一些厉害的框架。接下来看看Scala的4个强大框架以及其优点和...

数据星河
35分钟前
0
0
天猫双 11 背后:409 亿次安全保护,全链路保障每个购物场景

2135 亿元!2018 天猫双 11 再次刷新纪录。 这一数字背后,为了让用户更畅快买买买,一个简单的点击下单过程,就有百余项阿里安全技术在保驾护航:全天拦截 16 亿次恶意攻击、保护 409 亿次用...

Mr_zebra
41分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部