本文主要研究下spring cloud gateway的RedirectToGatewayFilterhtml
spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.javajava
@Configuration @ConditionalOnProperty(name = "spring.cloud.gateway.enabled", matchIfMissing = true) @EnableConfigurationProperties @AutoConfigureBefore(HttpHandlerAutoConfiguration.class) @AutoConfigureAfter({GatewayLoadBalancerClientAutoConfiguration.class, GatewayClassPathWarningAutoConfiguration.class}) @ConditionalOnClass(DispatcherHandler.class) public class GatewayAutoConfiguration { //...... @Bean public RedirectToGatewayFilterFactory redirectToGatewayFilterFactory() { return new RedirectToGatewayFilterFactory(); } //...... }
spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/factory/RedirectToGatewayFilterFactory.javaspring
public class RedirectToGatewayFilterFactory extends AbstractGatewayFilterFactory<RedirectToGatewayFilterFactory.Config> { public static final String STATUS_KEY = "status"; public static final String URL_KEY = "url"; public RedirectToGatewayFilterFactory() { super(Config.class); } @Override public List<String> shortcutFieldOrder() { return Arrays.asList(STATUS_KEY, URL_KEY); } @Override public GatewayFilter apply(Config config) { return apply(config.status, config.url); } public GatewayFilter apply(String statusString, String urlString) { final HttpStatus httpStatus = parse(statusString); Assert.isTrue(httpStatus.is3xxRedirection(), "status must be a 3xx code, but was " + statusString); final URL url; try { url = URI.create(urlString).toURL(); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid url " + urlString, e); } return apply(httpStatus, url); } public GatewayFilter apply(HttpStatus httpStatus, URL url) { return (exchange, chain) -> chain.filter(exchange).then(Mono.defer(() -> { if (!exchange.getResponse().isCommitted()) { setResponseStatus(exchange, httpStatus); final ServerHttpResponse response = exchange.getResponse(); response.getHeaders().set(HttpHeaders.LOCATION, url.toString()); return response.setComplete(); } return Mono.empty(); })); } public static class Config { String status; String url; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } }
spring: cloud: gateway: routes: - id: prefixpath_route uri: http://example.org filters: - RedirectTo=302, http://acme.org
spring cloud gateway提供了RedirectToGatewayFilter,能夠直接在配置文件對指定的路由進行3xx跳轉。app