Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding programmatically new route to zuul proxy

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

like image 771
Gerardo Navarro Suarez Avatar asked Aug 05 '16 15:08

Gerardo Navarro Suarez


1 Answers

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.

like image 64
wheeler Avatar answered Oct 28 '22 19:10

wheeler