Spring Cloud Gateway确实是新来的-但它“似乎”足够容易。我真的很挣扎的一个问题。我的要求是在路径前添加前缀,检查标头变量,基于该变量查找URI,然后进行调试。
问题是,即使我在idResolvingGatewayFilter中进行了更改,uri也始终是下面的DEFAULT_IMPLEMENTION。我该怎么做?可以随时添加新ID-这就是“动态”部分。因此,在网关过滤器中,我正在读取标头并查找uri(我正在查看的数据源可以随时更新)。但是下面的代码似乎覆盖了我在过滤器中分配的所有内容-如果不提供URI,则无法执行此操作。例如:
header-id = 123
uri = http://www.somedestination.com/something/services/v1.0
header-id = 999
uri = http://www.anotherdestination.com/something/services/v1.0
@Bean
public RouteLocator rosterRouteLocator( RouteLocatorBuilder builder )
{
log.info( "Establishing Gateway Routes" );
return builder.routes()
.route( r -> r.path( "/**" ).filters( f -> f.prefixPath( "/something/services/v1.0" ).filter( idResolvingGatewayFilter() ) )
.uri( resolver.buildDestinationEndpoint( IdUrlResolver.DEFAULT_IMPLEMENTATION ) ) )
.build();
}
然后在idResolvingGatewatFilter中进行更改(并且log语句看起来是正确的……它只是不行了!
public Mono<Void> filter( ServerWebExchange exchange, GatewayFilterChain chain )
{
try
{
URI newUri = buildURI( exchange );
ServerHttpRequest request = exchange.getRequest().mutate().uri( newUri ).build();
exchange = exchange.mutate().request( request ).build();
log.debug( "Modified URI: " + exchange.getRequest().getURI() );
答案 0 :(得分:0)
@SpringBootApplication
public class SpringCloudGatewayApplication {
@Autowired
private CustomerFilter filter;
public static void main(String[] args) {
SpringApplication.run(SpringCloudGatewayApplication.class, args);
}
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes().route(p -> p.path("/**").filters(f -> f.filter(filter)).uri("no://op")).build();
}
}
class CustomerFilter implements GatewayFilter, Ordered {
@Override
public int getOrder() {
return RouteToRequestUrlFilter.ROUTE_TO_URL_FILTER_ORDER + 1;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String newUrl = null;
if (exchange.getRequest().getHeaders().getHost().toString().equals("localhost:8080")) {
newUrl = "http://ip1/path1";
} else {
newUrl = "http://ip2/path2";
}
exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, new URI(newUrl));
return chain.filter(exchange);
}
}