欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot zuul 动态路由的实现

程序员文章站 2022-06-03 19:00:44
...

之前文章讲过zuul使用的filter进行路由等信息配置

PreDecorationFilter 进行路由查找,他依托RouteLocator进行查找

Spring Cloud默认的路由定位器由SimpleRouteLocator来实现

SimpleRouteLocator代码如下

@Override
public Route getMatchingRoute(final String path) {

   return getSimpleMatchingRoute(path);

}
protected Route getSimpleMatchingRoute(final String path) {
   if (log.isDebugEnabled()) {
      log.debug("Finding route for path: " + path);
   }

   // This is called for the initialization done in getRoutesMap()
   getRoutesMap();

   if (log.isDebugEnabled()) {
      log.debug("servletPath=" + this.dispatcherServletPath);
      log.debug("zuulServletPath=" + this.zuulServletPath);
      log.debug("RequestUtils.isDispatcherServletRequest()="
            + RequestUtils.isDispatcherServletRequest());
      log.debug("RequestUtils.isZuulServletRequest()="
            + RequestUtils.isZuulServletRequest());
   }

   String adjustedPath = adjustPath(path);

   ZuulRoute route = getZuulRoute(adjustedPath);

   return getRoute(route, adjustedPath);
}
protected Map<String, ZuulRoute> getRoutesMap() {
   if (this.routes.get() == null) {
      this.routes.set(locateRoutes());
   }
   return this.routes.get();
}
protected Map<String, ZuulRoute> locateRoutes() {
   LinkedHashMap<String, ZuulRoute> routesMap = new LinkedHashMap<>();
   for (ZuulRoute route : this.properties.getRoutes().values()) {
      routesMap.put(route.getPath(), route);
   }
   return routesMap;
}

使用继承这默认的SimpleRouteLocator  实现protected方法locateRoutes ,可以改成从数据库里面查询,也可以改成zk查询

 

路由动态刷新

org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator#doRefresh  zuul的路由刷新是通过该方法刷新的

 

zuul内部提供了ZuulRefreshListener,它会监听ApplicationEventPublisher发布的事件,如果事件为RoutesRefreshedEvent,则会调用routeLocator的refresh函数,

然后在自定义的路由定位器中可以直接调用SimpleRouteLocator的doRefresh函数

相关标签: springcloud