Spring Cloud Gateway 动态路由
Posted
技术标签:
【中文标题】Spring Cloud Gateway 动态路由【英文标题】:Spring Cloud Gateway Dynamic Routing 【发布时间】:2019-03-31 13:02:23 【问题描述】:对 Spring Cloud Gateway 来说真的很新——但它“似乎”很容易。我真的在努力解决一个问题。我的要求是为路径添加前缀,检查标头变量,根据该变量查找 URI,然后再进行检查。
问题是 uri 始终是下面的 DEFAULT_IMPLEMENTION,即使我在 idResolvingGatewayFilter 中更改了它。我怎样才能做到这一点?可以随时添加新的 id - 这就是“动态”部分。所以在网关过滤器中,我正在读取标题并查找 uri(我正在查看的数据源可以随时更新)。但是下面的代码似乎覆盖了我在过滤器中分配的任何内容 - 如果不提供 URI,您将无法执行此操作。例如:
标头 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() );
【问题讨论】:
【参考方案1】:@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 2.x版本 Gateway动态路由教程
spring cloud 2.x版本 Gateway动态路由教程
Spring Cloud Gateway——实现路由动态修改
Spring Cloud Gateway——实现路由动态修改