我正在使用带有@EnableZuulProxy
注释的spring boot应用程序。但我想在运行时添加自定义路由。这怎么可能?
现有文档仅显示静态示例,其中路由在application.yml
中定义。你能指点我用例的代码片段吗?
在ZuulConfiguration
我发现添加路由routeLocator().getRoutes().add(route);
的可能性,但它们不适用于运行时。我错过了什么?
非常感谢。干杯
了Gerardo
答案 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),但这应该提供如何开始的要点。