我正在尝试使用 Spring Cloud Gateway 为以下场景定义路由:
http://gateway-url/service-url?token=foo_bar => 被转发到服务 url。
http://gateway-url/service-url => 被转发到其他地方
这就是我到目前为止所得到的。
@Bean
public RouteLocator customRouteLocator( RouteLocatorBuilder builder,
RouteServiceForwardingFilter forwardingFilter) {
return builder.routes()
.route(r ->
r.query("token")
.filters(f -> {
f.filter(forwardingFilter, ROUTE_TO_URL_FILTER_ORDER + 1);
return f;
})
.uri("http://google.com:80")
.id("token_route"))
.build();
}
这是我创建的过滤器
@Component
public class RouteServiceForwardingFilter implements GatewayFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
try {
String forwardUrl = exchange.getRequest().getURI().toString();
forwardUrl = forwardUrl.substring(0, forwardUrl.lastIndexOf("?"));
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, new URI(forwardUrl));
return chain.filter(exchange);
} catch (URISyntaxException e) {
exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
return Mono.empty();
}
}
}