上一篇文章:zuul实现所有接口对于带指定前缀和不带前缀的url均能兼容访问
上一篇文章里我们说了SimpleRouteLocator类中根据url路径获取Route主要分为4步,上一篇文章主要说了第2步url路径的预处理,现在我们继续讲其它3步。
//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()
//1.获取ZuulRoute的映射对
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());
}
//2.对url路径预处理
String adjustedPath = adjustPath(path);
//3.根据路径获取匹配的ZuulRoute
ZuulRoute route = getZuulRoute(adjustedPath);
//4.根据ZuulRoute组装Route
return getRoute(route, adjustedPath);
}
1…获取ZuulRoute的映射对getRoutesMap();
protected Map<String, ZuulRoute> getRoutesMap() {
if (this.routes.get() == null) {
this.routes.set(locateRoutes());
}
return this.routes.get();
}
从本地线程变量获取,weinull则调用locateRoutes方法。
接下来我们以DiscoveryClientRouteLocator类为例讲解locateRoutes方法。
@Override
protected LinkedHashMap<String, ZuulRoute> locateRoutes() {
LinkedHashMap<String, ZuulRoute> routesMap = new LinkedHashMap<>();
//1.1首先调用父类SimpleRouteLocator的方法
routesMap.putAll(super.locateRoutes());
if (this.discovery != null) {
//1.2根据routesMap遍历组装成新的映射对staticServices,serveiceId为key值
Map<String, ZuulRoute> staticServices = new LinkedHashMap<>();
for (ZuulRoute route : routesMap.values()) {
String serviceId = route.getServiceId();
if (serviceId == null) {
serviceId = route.getId();
}
if (serviceId != null) {
staticServices.put(serviceId, route);
}
}
// Add routes for discovery services by default
//1.3对于发现的服务,按照一定规则加入routesMap
List<String> services = this.discovery.getServices();
String[] ignored = this.properties.getIgnoredServices()
.toArray(new String[0]);
for (String serviceId : services) {
// Ignore specificall