以编程方式添加到zuul代理的新路由

时间:2016-08-05 15:59:15

标签: spring spring-boot routing netflix-zuul

我正在使用带有@EnableZuulProxy注释的spring boot应用程序。但我想在运行时添加自定义路由。这怎么可能?

现有文档仅显示静态示例,其中路由在application.yml中定义。你能指点我用例的代码片段吗?

ZuulConfiguration我发现添加路由routeLocator().getRoutes().add(route);的可能性,但它们不适用于运行时。我错过了什么?

非常感谢。干杯

了Gerardo

1 个答案:

答案 0 :(得分:1)

我所做的是使用我自己的SimpleRouteLocator类将RouteLocator类子类化。以下是我所做的示例:

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(serveletPath, 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);
        }
    }
}

我不确定何时调用ServiceWatcher,因为在我的实际代码中ServiceWatcher包围了Kubernetes Watcher(因为我在OpenShift环境中运行Zuul),但这应该提供如何开始的要点。