【问题标题】:Adding programmatically new route to zuul proxy以编程方式向 zuul 代理添加新路由
【发布时间】:2016-12-12 02:48:00
【问题描述】:

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

现有文档仅显示静态示例,其中路由在application.yml 中定义。您能否指出我的用例的 sn-ps 代码。

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

非常感谢。干杯

杰拉尔多

【问题讨论】:

  • 你好@Gerardo,你已经解决了这个问题吗?谢谢

标签: spring spring-boot routing netflix-zuul


【解决方案1】:

我所做的是用我自己的 RouteLocator 类继承 SimpleRouteLocator 类。这是我所做的示例:

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);
        }
    }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 2014-11-10
    • 2015-03-06
    • 2015-06-18
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多