摘要:Spring Cloud Gateway只有两种类型的Filter,本文介绍如何在Spring Cloud Gateway中创建一个Pre或Post类型的Filter。

zuul的Filter类型

Zuul 的 Filter 是通过filterType()方法来指定,一个 Filter 只能对应一种类型,要么是 “pre” 要么是“post”

Spring Cloud Gateway的Filter类型

Spring Cloud Gateway 基于 Project Reactor 和 WebFlux,采用响应式编程风格,打开它的 Filter 的接口GatewayFilter你会发现它只有一个方法filter

Pre类型的Filter

在Spring Cloud Gateway源码中定义了一个Pre类型的Filter,code将会在chain.filter() 之前被执行,代码:AddRequestHeader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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());
};
}

}

Post类型的Filter

对于Post类型的Filter,SetStatus
代码将会在chain.filter(exchange).then()里面的代码运行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class SetStatusGatewayFilterFactory extends AbstractGatewayFilterFactory<SetStatusGatewayFilterFactory.Config> {
@Override
public GatewayFilter apply(Config config) {
final HttpStatus status = ServerWebExchangeUtils.parse(config.status);
return (exchange, chain) -> {

return chain.filter(exchange).then(Mono.fromRunnable(() -> {
// check not really needed, since it is guarded in setStatusCode,
// but it's a good example
if (!exchange.getResponse().isCommitted()) {
setResponseStatus(exchange, status);
}
}));
};
}
}
感谢您的阅读,本文由 许进沉思录-专注于互联网与中间件基础架构技术研究 版权所有。如若转载,请注明出处:许进沉思录-专注于互联网与中间件基础架构技术研究(http://xujin.org/sc/gw/gw06/
公益Eureka Server与定制方法
Spring Cloud Gateway基于服务发现的默认路由规则