gpt4 book ai didi

spring-cloud-gateway - Spring Cloud Gateway 动态路由

转载 作者:行者123 更新时间:2023-11-30 23:45:56 24 4
gpt4 key购买 nike

Spring Cloud Gateway 真的很新 - 但它“似乎”很容易。我真的很苦恼的一个问题。我的要求是为路径添加前缀,检查头变量,根据该变量查找 URI,然后继续前进。

问题是 uri 总是下面的 DEFAULT_IMPLEMENTION,即使我在 idResolvingGatewayFilter 中更改了它。我怎样才能做到这一点?可以随时添加新 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 中,我正在进行更改(并且日志语句看起来是正确的……它只是不去那里!
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() );

最佳答案

@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);
}
}

关于spring-cloud-gateway - Spring Cloud Gateway 动态路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53014301/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com