我有一个自定义网关过滤器MYGatewayFilter.java文件现在我想使用这个网关过滤器和我在application.yml中编写的路由
spring:
cloud:
gateway:
routes:
- id: login2_route
uri: http://127.0.0.1:8083/login
predicates:
- Path: /login/
filters:
如何为上述路线定义过滤器
自定义过滤器MyGatewayFilter.java
public class MyGatewayFilter implements GatewayFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request;
if(request.getHeaders().get("x-mydata")!=null){
request= exchange.getRequest().mutate().header("my-new-header",request.getHeaders().get("x-mydata").get(0)).build();
}
return chain.filter(exchange.mutate().request(request).build());
}
}
答案 0 :(得分:12)
您应该实现GatewayFilterFactory
,而不是实现GatewayFilter并将其设为组件:
Manure
然后你可以通过路线中的豆子名称来引用它。
@Component
public class MyGatewayFilter implements GatewayFilterFactory {
目前关于此的文档并不是很好。我只能通过查看github上的spring-cloud-gateway的源代码来解决这个问题
答案 1 :(得分:3)
您需要实现GatewayFilterFactory
@Component
public class DemoGatewayFilter implements GatewayFilterFactory<DemoGatewayFilter.Config> {
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
System.out.println("gateway filter name "+config.getName());
return chain.filter(exchange);
};
}
@Override
public Config newConfig() {
return new Config("DemoGatewayFilter");
}
public static class Config {
public Config(String name){
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
和位于application.yml文件中
spring:
application:
cloud:
gateway:
routes:
- id: MayApplication
uri: http://myapplication:8080
predicates:
- Path=/apipath/to/filter/**
filters:
- DemoGatewayFilter
答案 2 :(得分:0)
我认为Spring Cloud Gateway 2.2.1进行了一些更改。
我指的是SaveSessionGatewayFilterFactory.java。
@Component
public class DemoGatewayFilter implements AbstractGatewayFilterFactory {
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
return chain.filter(exchange);
};
/*
it works too
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return chain.filter(exchange);
}
}
*/
}
}
和application.yml文件中的
spring:
application:
cloud:
gateway:
routes:
- id: MayApplication
uri: http://myapplication:8080
predicates:
- Path=/api/path/to/filter/**
filters:
- DemoGatewayFilter