Delete zuul route dynamically without restarting the gateway
You can extend DiscoveryClientRouteLocator
and add removeRoute()
method:
Here is my example of this
@SpringBootApplication
@EnableZuulProxy
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
public static class DeregistrableDiscoveryClientRouteLocator extends DiscoveryClientRouteLocator {
private final ZuulProperties properties;
public DeregistrableDiscoveryClientRouteLocator(String servletPath, DiscoveryClient discovery, ZuulProperties properties, ServiceInstance localServiceInstance) {
super(servletPath, discovery, properties, localServiceInstance);
this.properties = properties;
}
public DeregistrableDiscoveryClientRouteLocator(String servletPath, DiscoveryClient discovery, ZuulProperties properties, ServiceRouteMapper serviceRouteMapper, ServiceInstance localServiceInstance) {
this(servletPath, discovery, properties, localServiceInstance);
}
//here is new method to remove route from .properties.getRoutes()
public void removeRoute(String path) {
this.properties.getRoutes().remove(path);
refresh();
}
}
@Bean
DiscoveryClientRouteLocator discoveryClientRouteLocator(ServerProperties server, ZuulProperties zuulProperties, DiscoveryClient discovery, ServiceRouteMapper serviceRouteMapper, @Autowired(required = false) Registration registration) {
return new DeregistrableDiscoveryClientRouteLocator(server.getServlet().getContextPath(),
discovery, zuulProperties, serviceRouteMapper,
registration);
}
@Component
public static class AppRunner implements ApplicationRunner {
@Autowired
DeregistrableDiscoveryClientRouteLocator discoveryClientRouteLocator;
@Override
public void run(ApplicationArguments args) throws Exception {
ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute();
zuulRoute.setId("google");
zuulRoute.setServiceId("google");
zuulRoute.setPath("/");
zuulRoute.setUrl("http://google.com");
zuulRoute.setRetryable(true);
discoveryClientRouteLocator.addRoute(zuulRoute);
//now remove the pre-added route.
discoveryClientRouteLocator.removeRoute(zuulRoute.getPath());
}
}
}
So after that you can create a rest endpoint which will remove a route without restarting the server.