1 | initial version |
To redirect to another host using Spring Cloud Gateway, you can follow these steps:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
Create a configuration class that extends org.springframework.cloud.gateway.config.GatewayConfiguation
.
Inside the configuration class, define a bean of type org.springframework.cloud.gateway.route.RouteLocator
.
In the bean definition, use the routes()
method to define a route using the Route.async()
method. This method takes a Predicate<ServerWebExchange>
to match the incoming request, and a Function<GatewayFilterSpec, UriSpec>
to define the destination URI of the route.
Use the uri()
method of the UriSpec
to specify the target URI for the redirection.
Build the route by chaining additional filters as needed, and then return the completed route.
Here's an example configuration class that redirects requests for any path under /foo
to a different host:
@Configuration
public class GatewayConfiguration extends GatewayConfiguation {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route(r -> r.path("/foo/**")
.filters(f -> f.redirect(302, "http://another.host.com/foo"))
.uri("http://another.host.com"))
.build();
}
}
In this example, r.path("/foo/**")
matches any path that starts with /foo
, and f.redirect(302, "http://another.host.com/foo")
specifies a 302 redirect to http://another.host.com/foo
.