Spring Cloud Gateway Dynamic Routing

Spring Cloud Gateway Dynamic Routing

@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 Dynamic Routing

Leave a Reply

Your email address will not be published. Required fields are marked *