我正在使用带有 @EnableZuulProxy
的 Spring Boot 应用程序注解。但我想在运行时添加自定义路由。这怎么可能?
现有文档仅显示静态示例,其中路由在 application.yml
中定义。 .您能否指出我的用例的代码片段。
在 ZuulConfiguration
我发现可以添加路线 routeLocator().getRoutes().add(route);
但它们不适用于运行时。我错过了什么?
非常感谢。干杯
杰拉尔多
请您参考如下方法:
我所做的是子类化 SimpleRouteLocator
和我自己一起上课 RouteLocator
类(class)。这是我所做的示例:
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),但这应该提供如何开始的要点。