SpringCloud Gateway自动装配实现流程详解

目录
  • 启动依赖
  • WebFluxAutoConfiguration
  • HttpHandlerAutoConfiguration
  • 总结一下

启动依赖

找到gateway的依赖,spring-cloud-starter-gateway

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

点进去之后找到它的依赖

  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter</artifactId>
      <version>3.1.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-gateway-server</artifactId>
      <version>3.1.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webflux</artifactId>
      <version>2.6.3</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-loadbalancer</artifactId>
      <version>3.1.1</version>
      <scope>compile</scope>
      <optional>true</optional>
    </dependency>
  </dependencies>

从名称上可以判断spring-cloud-gateway-server是gateway的核心依赖,找到依赖包,看到如下结构

spring.factories是一些自动装配的类,如下可以看到

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.gateway.config.GatewayClassPathWarningAutoConfiguration,\
org.springframework.cloud.gateway.config.GatewayAutoConfiguration,\
org.springframework.cloud.gateway.config.GatewayResilience4JCircuitBreakerAutoConfiguration,\
org.springframework.cloud.gateway.config.GatewayNoLoadBalancerClientAutoConfiguration,\
org.springframework.cloud.gateway.config.GatewayMetricsAutoConfiguration,\
org.springframework.cloud.gateway.config.GatewayRedisAutoConfiguration,\
org.springframework.cloud.gateway.discovery.GatewayDiscoveryClientAutoConfiguration,\
org.springframework.cloud.gateway.config.SimpleUrlHandlerMappingGlobalCorsAutoConfiguration,\
org.springframework.cloud.gateway.config.GatewayReactiveLoadBalancerClientAutoConfiguration,\
org.springframework.cloud.gateway.config.GatewayReactiveOAuth2AutoConfiguration

org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.cloud.gateway.config.GatewayEnvironmentPostProcessor

# Failure Analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.cloud.gateway.support.MvcFoundOnClasspathFailureAnalyzer

其中比较重要的是GatewayAutoConfiguration,负责很多bean的初始化,类声明如下:

@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "spring.cloud.gateway.enabled", matchIfMissing = true)
@EnableConfigurationProperties
@AutoConfigureBefore({ HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class })
@AutoConfigureAfter({ GatewayReactiveLoadBalancerClientAutoConfiguration.class,
		GatewayClassPathWarningAutoConfiguration.class })
@ConditionalOnClass(DispatcherHandler.class)
public class GatewayAutoConfiguration {			

@AutoConfigureBefore@AutoConfigureAfter分别是在之前和之后加载

其中HttpHandlerAutoConfigurationWebFluxAutoConfiguration算是比较重要的装配类

WebFluxAutoConfiguration

先看WebFluxAutoConfiguration,类声明如下:

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnClass(WebFluxConfigurer.class)
@ConditionalOnMissingBean({ WebFluxConfigurationSupport.class })
@AutoConfigureAfter({ ReactiveWebServerFactoryAutoConfiguration.class, CodecsAutoConfiguration.class,
		ReactiveMultipartAutoConfiguration.class, ValidationAutoConfiguration.class,
		WebSessionIdResolverAutoConfiguration.class })
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
public class WebFluxAutoConfiguration {

其中部分代码如下:

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({ WebProperties.class, WebFluxProperties.class })
@Import({ EnableWebFluxConfiguration.class })
@Order(0)
public static class WebFluxConfig implements WebFluxConfigurer {

可以看到通过WebFluxAutoConfiguration 通过 WebFluxConfig 导入了 EnableWebFluxConfiguration

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({ WebProperties.class, ServerProperties.class })
public static class EnableWebFluxConfiguration extends DelegatingWebFluxConfiguration {

EnableWebFluxConfiguration继承于DelegatingWebFluxConfiguration

@Configuration(proxyBeanMethods = false)
public class DelegatingWebFluxConfiguration extends WebFluxConfigurationSupport {

DelegatingWebFluxConfiguration又继承于WebFluxConfigurationSupport

在WebFluxConfigurationSupport中可以看到很熟悉的东西

@Bean
public DispatcherHandler webHandler() {
    //BeanName为webHandler
	return new DispatcherHandler();
}

有点联想到DispatcherSerlvet,类似前端控制器

public class DispatcherHandler implements WebHandler, PreFlightRequestHandler, ApplicationContextAware {<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E-->

可以看到DispatcherHandler实现了WebHandler接口并实现了其中的handle方法

public interface WebHandler {
	/**
	 * Handle the web server exchange.
	 * @param exchange the current server exchange
	 * @return {@code Mono<Void>} to indicate when request handling is complete
	 */
	Mono<Void> handle(ServerWebExchange exchange);
}

可以猜到handle应该就是核心的处理方法,此时又有疑问,该方法什么时候被调用,被谁调用的

官方文档上提到WebHandler 上面还有一个关键的 API HttpHandler

For server request processing there are two levels of support.

HttpHandler: Basic contract for HTTP request handling with non-blocking I/O and Reactive Streams back pressure, along with adapters for Reactor Netty, Undertow, Tomcat, Jetty, and any Servlet 3.1+ container.

WebHandler API: Slightly higher level, general-purpose web API for request handling, on top of which concrete programming models such as annotated controllers and functional endpoints are built.

从上面的英文可以看到 HttpHandler 是比 WebHandler 更加底层的一个 API,也就是说很可能是由 HttpHandler 来调用 WebHandler (请求由下往上),那DispatcherHandler作为 WebHandler 的一个实现,也很有可能会被HttpHandler的具体实现所持有。

通过HttpHandler的实现类不难找到HttpWebHandlerAdapter 就是我们要找的,并且持有一个WebHandher 对象,当然也可以通过断点调试找到。

public class HttpWebHandlerAdapter extends WebHandlerDecorator implements HttpHandler {<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E-->

HttpWebHandlerAdapter继承于WebHandlerDecorator

public class WebHandlerDecorator implements WebHandler {
	private final WebHandler delegate;
	/**
	 * Return the wrapped delegate.
	 */
	public WebHandler getDelegate() {
		return this.delegate;
	}

可以看到WebHandlerDecorator持有WebHandler对象

总之,我们找到了调用 DispatcherHandher 的地方了,那下一步我们要找 HttpWebHandlerAdapter 是在哪里被装配的,并且webHandler 是是什么时候被注入的,注入的 webHandler 是否就是 DispatcherHandler?

HttpHandlerAutoConfiguration

前面说过的另外一个装配类HttpHandlerAutoConfiguration

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ DispatcherHandler.class, HttpHandler.class })
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnMissingBean(HttpHandler.class)
@AutoConfigureAfter({ WebFluxAutoConfiguration.class })
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
public class HttpHandlerAutoConfiguration {
	@Configuration(proxyBeanMethods = false)
	public static class AnnotationConfig {
		private final ApplicationContext applicationContext;
		public AnnotationConfig(ApplicationContext applicationContext) {
			this.applicationContext = applicationContext;
		}
		@Bean
		public HttpHandler httpHandler(ObjectProvider<WebFluxProperties> propsProvider) {
			HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(this.applicationContext).build();
			WebFluxProperties properties = propsProvider.getIfAvailable();
			if (properties != null && StringUtils.hasText(properties.getBasePath())) {
				Map<String, HttpHandler> handlersMap = Collections.singletonMap(properties.getBasePath(), httpHandler);
				return new ContextPathCompositeHandler(handlersMap);
			}
			return httpHandler;
		}
	}
}

可以看到这里注入了一个HttpHandler对象,难道就是HttpWebHandlerAdapter ,继续往下看

首先调用了WebHttpHandlerBuilder.applicationContext(this.applicationContext)方法,点进去看

	public static WebHttpHandlerBuilder applicationContext(ApplicationContext context) {
		WebHttpHandlerBuilder builder = new WebHttpHandlerBuilder(
				context.getBean(WEB_HANDLER_BEAN_NAME, WebHandler.class), context);
	    ......
		return builder;		

可以看到通过context上下文对象通过beanName获取bean来作为参数初始化WebHttpHandlerBuilder对象

/** Well-known name for the target WebHandler in the bean factory. */
public static final String WEB_HANDLER_BEAN_NAME = "webHandler";

而这个beanName正式前面说过的DispatcherHandler对象

	private WebHttpHandlerBuilder(WebHandler webHandler, @Nullable ApplicationContext applicationContext) {
		Assert.notNull(webHandler, "WebHandler must not be null");
		this.webHandler = webHandler;
		this.applicationContext = applicationContext;
	}

WebHttpHandlerBuilder中的webHandler属性赋值为DispatcherHandler对象

接着进入build()方法,整体可以看到返回的HttpHandler对象就是HttpWebHandlerAdapter

	public HttpHandler build() {
		WebHandler decorated = new FilteringWebHandler(this.webHandler, this.filters);
		decorated = new ExceptionHandlingWebHandler(decorated,  this.exceptionHandlers);
		HttpWebHandlerAdapter adapted = new HttpWebHandlerAdapter(decorated);
		if (this.sessionManager != null) {
			adapted.setSessionManager(this.sessionManager);
		}
		if (this.codecConfigurer != null) {
			adapted.setCodecConfigurer(this.codecConfigurer);
		}
		if (this.localeContextResolver != null) {
			adapted.setLocaleContextResolver(this.localeContextResolver);
		}
		if (this.forwardedHeaderTransformer != null) {
			adapted.setForwardedHeaderTransformer(this.forwardedHeaderTransformer);
		}
		if (this.applicationContext != null) {
			adapted.setApplicationContext(this.applicationContext);
		}
		adapted.afterPropertiesSet();
		return (this.httpHandlerDecorator != null ? this.httpHandlerDecorator.apply(adapted) : adapted);
	}

首先看第一行

//这里的webHandler就是DispatcherHandler对象
WebHandler decorated = new FilteringWebHandler(this.webHandler, this.filters);
	public FilteringWebHandler(WebHandler handler, List<WebFilter> filters) {
		super(handler);
		this.chain = new DefaultWebFilterChain(handler, filters);
	}

调用父类的构造方法

private final WebHandler delegate;
public WebHandlerDecorator(WebHandler delegate) {
		Assert.notNull(delegate, "'delegate' must not be null");
		this.delegate = delegate;
	}

此时将delegate赋值为DispatcherHandler对象

接着第二行

//此时入参中的decorated是FilteringWebHandler对象
decorated = new ExceptionHandlingWebHandler(decorated,  this.exceptionHandlers);
	public ExceptionHandlingWebHandler(WebHandler delegate, List<WebExceptionHandler> handlers) {
		super(delegate);
		List<WebExceptionHandler> handlersToUse = new ArrayList<>();
		handlersToUse.add(new CheckpointInsertingHandler());
		handlersToUse.addAll(handlers);
		this.exceptionHandlers = Collections.unmodifiableList(handlersToUse);
	}

再次调用父类的构造方法将此对象的父类中delegate属性赋值为FilteringWebHandler对象

接着第三行

HttpWebHandlerAdapter adapted = new HttpWebHandlerAdapter(decorated);
	public HttpWebHandlerAdapter(WebHandler delegate) {
		super(delegate);
	}

一样的道理将父类中delegate属性赋值为ExceptionHandlingWebHandler对象

总结一下

HttpWebHandlerAdapter中delegate保存的是ExceptionHandlingWebHandler

ExceptionHandlingWebHandler中的delegate保存的是FilteringWebHandler

FilteringWebHandler中的delegate保存的是DispatcherHandler

到此这篇关于SpringCloud Gateway自动装配实现流程详解的文章就介绍到这了,更多相关SpringCloud Gateway内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • SpringCloud Gateway路由组件详解

    目录 简介 核心概念 具体示例 GlobalFilter 简介   Gateway是SpringCloud Alibaba中的路由组件(前身是Zuul),作为浏览器端请求的统一入口.当项目采用微服务模式时,若包含了路由模块,浏览器端的请求都不会直接请求含有业务逻辑的各个业务模块,而是请求这个路由模块,然后再由它来转发到各个业务模块去. 核心概念   Gateway中的三个核心概念:路由.断言(Predicate).过滤器.   路由:由唯一id.目的url.断言和过滤组成   断言:即路由规则,

  • SpringCloud Gateway动态转发后端服务实现过程讲解

    目录 前言 一.概述 二.项目中加入依赖 三.配置文件 四.动态路由数据存储格式 五.后端服务动态转发 六.单元测试 前言 API网关的核心功能是统一流量入口,实现路由转发,SpringCloudGateway是API网关开发的技术之一,此外比较流行的还有Kong和ApiSix,这2个都是基于OpenResty技术栈. 简单的路由转发可以通过SpringCloudGateway的配置文件实现,在一些业务场景种,会需要动态替换路由配置中的后端服务地址,单纯靠配置文件无法满足这种需求. 本文介绍一种

  • SpringCloud超详细讲解微服务网关Gateway

    目录 前言 微服务网关GateWay介绍 GateWay特性介绍 Gateway 中的相关术语 Gateway实战 1.创建项目gateway 2.创建启动类 3.新增配置文件 4.编程方式实现路由 5.启动验证 总结 前言 上一篇:微服务网关Zuul 上文中,我们介绍了微服务网关Zuul,Zuul 是 Netflix 公司开源的产品,被称为第一代网关,也是 Spring Cloud 前几个版本默认使用的一款提供动态路由微服务网关组件,但是随着 Netflix 公司一系列的停更事件,在最新的 S

  • SpringCloud中Gateway的使用教程详解

    目录 1.基础教程 2.将配置放在配置文件里 3.放在springcloud里面 4.使用服务名而不是IP 1.基础教程 pom.xml <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.6</version> </parent>

  • SpringCloud Gateway网关功能介绍与使用

    目录 一.什么是API网关 二.基本使用 三.谓词 四.过滤器-Filter 五.使用Gateway实现限流 六.使用Gateway实现服务降级 七.自定义全局过滤器 八.自定义路由过滤器 一.什么是API网关 API网关作用就是把各个服务对外提供的API汇聚起来,让外界看起来是一个统一的接口.同时也可在网关中提供额外的功能. 总结:网关就是所有项目的一个统一入口. 二.基本使用 1.准备Eureka注册中心 2.准备一个微服务工程 3.搭建Gateway网关微服务 (1)导入依赖 <depen

  • SpringCloud Gateway实现限流功能详解

    目录 1 什么是限流 2 本次限流模型 3 Gateway结合redis实现请求量限流 3.1 添加依赖 3.2 修改配置文件 3.3 配置文件说明 3.4 创建配置类RequestRateLimiterConfig 3.5 启动快速访问测试 1 什么是限流 通俗的说,限流就是 限制一段时间内,用户访问资源的次数 ,减轻服务器压力,限流大致分为两种: 1. IP 限流(5s 内同一个 ip 访问超过 3 次,则限制不让访问,过一段时间才可继续访问) 2. 请求量限流(只要在一段时间内(窗口期),

  • SpringCloud Gateway动态路由配置详解

    目录 路由 动态 路由模型实体类 动态路径配置 路由模型JSON数据 路由 gateway最主要的作用是,提供统一的入口,路由,鉴权,限流,熔断:这里的路由就是请求的转发,根据设定好的某些条件,比如断言,进行转发. 动态 动态的目的是让程序更加可以在运行的过程中兼容更多的业务场景. 涉及到两个服务,一个是门户服务(作用是提供给运营人员管理入口--包括:管理路由.绑定路由),一个是网关服务(gateway组件,为门户服务提供:查询路由信息.添加路由.删除路由.编辑路由接口). 路由模型实体类 /*

  • SpringCloud Gateway的路由,过滤器和限流解读

    目录 Spring Cloud Gateway predicates路由断言工厂 全局过滤器 fGatewayFilter工厂 filters配置 Hystrix GatewayFilter工厂 限流RequestRateLimiter GatewayFilter工厂 参考文档 总结 Spring 官方最终还是按捺不住推出了自己的网关组件:Spring Cloud Gateway ,相比之前我们使用的 Zuul(1.x) 它有哪些优势呢? Zuul(1.x) 基于 Servlet,使用阻塞 AP

  • SpringCloud服务网关Gateway的使用教程详解

    目录 Gateway 什么是Gateway 什么是api网关 网关的三个核心概念 路由(Route) 断言(Predicate) 过滤(Filter) gateway的工作流程 如何使用Gateway gateway路由转发 使用配置文件 使用代码配置 路由实现负载均衡 gateway九种断言 gateway过滤修改 Gateway 什么是Gateway   由于Netflix的zuul发生问题,spring公司自己研发了一套网关框架Gateway用于取代zuul的使用.什么是gateway呢?

  • SpringCloud注册中心部署Eureka流程详解

    目录 1.Eureka服务 2.服务提供者 3.服务消费者 4.服务调用测试 今天我们开始正式编码,如何创建spring boot项目这篇文章就不再讲述,如果想要了解可以阅读我之前的创建springboot项目. 首先我们先进行Spring cloud五大组件之一的注册中心,之前文章已经讲过注册中心的介绍,今天我们来部署Netflix的Eureka,进行单机部署以及高可用部署,并开发生产者以及消费者来进行测试eureka的注册消费.(ps:系列文章使用的Spring cloud版本为2021.0

  • SpringBoot 自动装配的原理详解分析

    目录 前言 自动装配案例 自动装配分析 自动装配总结 前言 关于 ​​SpringBoot​​​ 的自动装配功能,相信是每一个 ​​Java​​ 程序员天天都会用到的一个功能,但是它究竟是如何实现的呢?今天阿粉来带大家看一下. 自动装配案例 首先我们通过一个案例来看一下自动装配的效果,创建一个 ​​SpringBoot​​ 的项目,在 ​​pom​​ 文件中加入下面的依赖. <dependency> <groupId>org.springframework.boot</gro

  • Python实现自动填写脚本流程详解

    目录 前言 环境使用 模块使用 本次案例代码实现思路 最终效果 代码实现 前言 环境使用 Python 3.8 Pycharm 模块使用 import requests —> 数据请求模块 pip install requests import parsel —> 数据解析模块 pip install parsel from selenium import webdriver —> 自动测试模块 pip install selenium==3.141.0 本次案例代码实现思路 打开考试网

  • Java注解机制之Spring自动装配实现原理详解

    Java中使用注解的情况主要在SpringMVC(Spring Boot等),注解实际上相当于一种标记语言,它允许你在运行时动态地对拥有该标记的成员进行操作.注意:spring框架默认不支持自动装配的,要想使用自动装配需要修改spring配置文件中<bean>标签的autowire属性. 自动装配属性有6个值可选,分别代表不同的含义: byName ->从Spring环境中获取目标对象时,目标对象中的属性会根据名称在整个Spring环境中查找<bean>标签的id属性值.如果

  • SpringBoot启动及自动装配原理过程详解

    一.servlet2(老spring-mvc) 配置文件: web.xml:主要配置项目启动项 application-context.xml:主要配置项目包扫描.各种bean.事务管理 springMVC.xml:主要配置controller包扫描.视图解析器.参数解析器 启动过程: 每一个spring项目启动时都需要初始化spring-context,对于非web项目可以在程序main方法中触发这个context的初始化过程. 由于web项目的启动入口在容器,所以开发者不能直接触发sprin

  • SpringCloud项目的log4j2漏洞解决方案详解流程

    步骤如下: <properties> <log4j2.version>2.15.0</log4j2.version> </properties> 下面为上边对应版本号的具体依赖 <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.15.

  • SpringBoot DataSource数据源实现自动配置流程详解

    目录 一.重点概念 1.什么是DataSource数据源 2.数据库连接池 二.导入依赖 三.分析自动配置 1.DataSourceAutoConfiguration类 2.DataSourceTransactionManagerAutoConfiguration类 3.JdbcTemplateAutoConfiguration类 4.JndiDataSourceAutoConfiguration类 5.XADataSourceAutoConfiguration类 四.代码样例 一.重点概念 1

  • Java nacos动态配置实现流程详解

    目录 一.前言 二.在nacos上创建配置文件 创建配置文件 配置说明 发布并检查配置文件 三. 修改项目配置与动态读取配置文件 添加 nacos 动态配置依赖 在controller与service中使用动态配置 四. 动态配置网关的使用 一.前言 使用动态配置的原因: properties 和 yaml 是写到项目中的,好多时候有些配置需要修改,每次修改就要重新启动项目,不仅增加了系统的不稳定性,也大大提高了维护成本,非常麻烦,且耗费时间. 使用动态配置,则可以避免这些麻烦,可以动态的修改配

  • SpringBoot实现服务接入nacos注册中心流程详解

    目录 概述 接入nacos注册中心 springboot服务pom文件 application.properties配置 源码分析 小结 源码流程图 概述 某些场景下只需要把springboot微服务化而不想引入springcloud如何实现的呢? 下面我们介绍nacos注册中心方案. 接入nacos注册中心 springboot服务pom文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="h

  • SpringMvc框架的简介与执行流程详解

    目录 一.SpringMvc框架简介 1.Mvc设计理念 2.SpringMvc简介 二.SpringMvc执行流程 1.流程图解 2.步骤描述 3.核心组件 三.整合Spring框架配置 1.spring-mvc配置 2.Web.xml配置 3.测试接口 4.常用注解说明 四.常见参数映射 1.普通映射 2.指定参数名 3.数组参数 4.Map参数 5.包装参数 6.Rest风格参数 五.源代码地址 一.SpringMvc框架简介 1.Mvc设计理念 M:代表模型Model 模型就是数据,应用

随机推荐