序
本文主要研究下spring cloud gateway的RedirectToGatewayFilter
GatewayAutoConfiguration
spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/config/GatewayAutoConfiguration.java
@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();
}
//......
}
RedirectToGatewayFilterFactory
spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/factory/RedirectToGatewayFilterFactory.java
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;
}
}
}
- 可以看到配置文件有两个参数,一个是status,一个是url
- 这里对status进行了校验,必须是3xx
- 然后设置response status code,同时在header的location写入要跳转的url
实例
spring:
cloud:
gateway:
routes:
- id: prefixpath_route
uri: http://example.org
filters:
- RedirectTo=302, http://acme.org
小结
spring cloud gateway提供了RedirectToGatewayFilter,可以直接在配置文件对指定的路由进行3xx跳转。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。