之前文章讲过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函数
本文深入探讨了Spring Cloud Zuul的路由配置机制,重点介绍了SimpleRouteLocator如何通过过滤器和自定义实现进行路由查找及动态刷新。揭示了路由定位器的内部工作原理,包括路径调整、路由获取和事件监听等关键环节。
1438

被折叠的 条评论
为什么被折叠?



