我是春天云网关的新手。
我一直在观看SpringDeveloper频道中的一些YouTube视频,我正在研究以下示例:
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route(r -> r.path("/get")
.addRequestHeader("X-SpringOne", "Awesome")
.uri("http://httpbin.org:80"))
.build();
}
在查看Spring cloud网关之前,我还看过Spring Netflix Zuul。我了解在Netflix Zuul中,您可以通过创建扩展ZuulFilter
的类并将其定义为pre
,post
,route
等来创建过滤器。
但是我想知道如何使用Spring云网关创建PRE / POST过滤器?
非常感谢任何帮助/建议。
感谢。
答案 0 :(得分:5)
对于预过滤器,此处为AddRequestHeader
(代码在chain.filter()
调用之前执行):
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());
};
}
}
对于'帖子'过滤器,这里是SetStatus
(代码在chain.filter(exchange).then()
中以lambda运行):
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);
}
}));
};
}
}
答案 1 :(得分:0)
以下是Kotlin中的一个简单示例:URI SELECT CASE WHEN COUNT(CASE WHEN age BETWEEN 18 AND 22 THEN empid END) = 0 THEN '' ELSE 'X' END AS Ka,
CASE WHEN COUNT(CASE WHEN age BETWEEN 23 AND 30 THEN empid END) = 0 THEN '' ELSE 'X' END AS Kb,
CASE WHEN COUNT(CASE WHEN age BETWEEN 31 AND 35 THEN empid END) = 0 THEN '' ELSE 'X' END AS Kc
FROM Employee;
映射到从发现服务获取的URI( lb = 负载平衡)名为http://.../customers
的服务并附加“/”。此外,转发的请求通过附加的标头条目得到增强。希望这会有所帮助。
customer
答案 2 :(得分:-1)
我不确定这是否是正确的方法,因为我也试图实现这种行为,我在想是否需要这样做:
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
public class CustomFilter implements GatewayFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//code for PRE filter
Mono<Void> v = chain.filter(exchange);
//code for POST filter
return v;
}
}
如果这对您有用或者您找到了另一种解决方案,请告诉我。