zuul路由转发源码解析

本文深入解析Zuul路由转发的源码实现,包括locateRoutes方法的详细步骤,如配置文件中的zuul.routes处理、服务发现、路由规则匹配逻辑,以及url路径的预处理。同时,介绍了PreDecorationFilter如何处理找不到路由时的fallback策略,并概述了不同转发目标的实现方式,如RibbonRoutingFilter、SimpleHostRoutingFilter和SendForwardFilter。
摘要由CSDN通过智能技术生成

上一篇文章: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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值