I am using a spring boot application with @EnableZuulProxy
annotation. But I would like to add custom routes during runtime. How is this possible?
Existing documentation only shows static examples, in which routes are defined in the application.yml
. Could you point me to code snippets of my use case.
In the ZuulConfiguration
I found a possibility to add routes routeLocator().getRoutes().add(route);
but they are not applied to the runtime. What am I missing?
Thanks a lot. Cheers
Gerardo
What I did was subclass the SimpleRouteLocator
class with my own RouteLocator
class. Here is sample of what I did:
public class RouteLocator extends SimpleRouteLocator implements RefreshableRouteLocator {
@Autowired
private ZuulHandlerMapping zuulHandlerMapping;
private Map<String, ZuulRoute> routes = new ConcurrentHashMap<>();
public RouteLocator(TaskExecutor executor, String servletPath, ZuulProperties properties) {
super(servletPath, properties);
executor.execute(new ServiceWatcher());
}
@Override
public Map<String, ZuulRoute> locateRoutes() {
return this.routes;
}
@Override void refresh() {
this.doRefresh();
}
private class ServiceWatcher implements Runnable {
@Override
public void run(){
// Add your routes to this.routes here.
ZuulRoute route1 = new ZuulRoute("/somePath", "http://someResourceUrl:8080");
ZuulRoute route2 = new ZuulRoute("/someOtherPath", "some-service-id");
routes.put("/somePath", route1);
routes.put("/someOtherPath", route2);
zuulHandlerMapping.setDirty(true);
}
}
}
I'm not exactly sure when the ServiceWatcher
gets called since in my actual code the ServiceWatcher
wraps around a Kubernetes Watcher
(since I am running Zuul in an OpenShift environment), but this should provide the gist of how to get started.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With