Spring Webflux DispatcherHandler源码整理

DispatcherHandler的构造(以RequestMappingHandlerMapping为例)
  1. WebFluxAutoConfiguration中EnableWebFluxConfiguration继承WebFluxConfigurationSupport
    @Bean
    public DispatcherHandler webHandler() {return new DispatcherHandler();
    }
    
  2. DispatcherHandler#setApplicationContext => initStrategies(applicationContext)
    protected void initStrategies(ApplicationContext context) {Map<String, HandlerMapping> mappingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);ArrayList<HandlerMapping> mappings = new ArrayList<>(mappingBeans.values());AnnotationAwareOrderComparator.sort(mappings);this.handlerMappings = Collections.unmodifiableList(mappings);//Map<String, HandlerAdapter> adapterBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false);//this.handlerAdapters = new ArrayList<>(adapterBeans.values());AnnotationAwareOrderComparator.sort(this.handlerAdapters);//Map<String, HandlerResultHandler> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerResultHandler.class, true, false);this.resultHandlers = new ArrayList<>(beans.values());AnnotationAwareOrderComparator.sort(this.resultHandlers);
    }
    
  3. RequestMappingHandlerMapping-> afterPropertiesSet -> AbstractHandlerMethodMapping.initHandlerMethods
    protected void initHandlerMethods() {String[] beanNames = obtainApplicationContext().getBeanNamesForType(Object.class);for (String beanName : beanNames) {if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {Class<?> beanType = obtainApplicationContext().getType(beanName);// 当类被Controller或则RequestMapping标注时查找HandlerMethodif (beanType != null && isHandler(beanType)) {detectHandlerMethods(beanName);}}}}
    
  4. AbstractHandlerMethodMapping#detectHandlerMethods(beanName)
     protected void detectHandlerMethods(final Object handler) {Class<?> handlerType = (handler instanceof String ?obtainApplicationContext().getType((String) handler) : handler.getClass());if (handlerType != null) {final Class<?> userType = ClassUtils.getUserClass(handlerType);Map<Method, T> methods = MethodIntrospector.selectMethods(userType,(MethodIntrospector.MetadataLookup<T>) method -> getMappingForMethod(method, userType));methods.forEach((method, mapping) -> {Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);// invocableMethod保存到MappingRegistry注册表中registerHandlerMethod(handler, invocableMethod, mapping);});}}
    
  5. RequestMappingHandlerMapping#getMappingForMethod(method, handlerType)
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {RequestMappingInfo info = createRequestMappingInfo(method);if (info != null) {RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);if (typeInfo != null) {info = typeInfo.combine(info);}for (Map.Entry<String, Predicate<Class<?>>> entry : this.pathPrefixes.entrySet()) {if (entry.getValue().test(handlerType)) {String prefix = entry.getKey();if (this.embeddedValueResolver != null) {prefix = this.embeddedValueResolver.resolveStringValue(prefix);}info = RequestMappingInfo.paths(prefix).options(this.config).build().combine(info);break;}}}return info;
    }
    
  6. RequestMappingHandlerMapping#createRequestMappingInfo(method)
    private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);RequestCondition<?> condition = (element instanceof Class ?getCustomTypeCondition((Class<?>) element) : getCustomMethodCondition((Method) element));return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null);
    }
    protected RequestMappingInfo createRequestMappingInfo(RequestMapping requestMapping, @Nullable RequestCondition<?> customCondition) {RequestMappingInfo.Builder builder = RequestMappingInfo.paths(resolveEmbeddedValuesInPatterns(requestMapping.path())).methods(requestMapping.method()).params(requestMapping.params()).headers(requestMapping.headers()).consumes(requestMapping.consumes()).produces(requestMapping.produces()).mappingName(requestMapping.name());if (customCondition != null) {builder.customCondition(customCondition);}return builder.options(this.config).build();}
    
DispatcherHandler的执行(以RequestMappingHandlerMapping为例)
查找handler
  1. DispatcherHandler#handle(exchange)
    public Mono<Void> handle(ServerWebExchange exchange) {if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {return handlePreFlight(exchange);}return Flux.fromIterable(this.handlerMappings).concatMap(mapping -> mapping.getHandler(exchange)).next().switchIfEmpty(createNotFoundError()).flatMap(handler -> invokeHandler(exchange, handler)).flatMap(result -> handleResult(exchange, result));
    }
    
  2. AbstractHandlerMapping#getHandler(exchange)
    public Mono<Object> getHandler(ServerWebExchange exchange) {return getHandlerInternal(exchange) ;
    }
    
  3. AbstractHandlerMethodMapping#getHandlerInternal
    public Mono<HandlerMethod> getHandlerInternal(ServerWebExchange exchange) {this.mappingRegistry.acquireReadLock();try {HandlerMethod handlerMethod;try {handlerMethod = lookupHandlerMethod(exchange);}catch (Exception ex) {return Mono.error(ex);}if (handlerMethod != null) {handlerMethod = handlerMethod.createWithResolvedBean();}return Mono.justOrEmpty(handlerMethod);}finally {this.mappingRegistry.releaseReadLock();}
    }
    
  4. AbstractHandlerMethodMapping#lookupHandlerMethod(exchange)
    protected HandlerMethod lookupHandlerMethod(ServerWebExchange exchange) throws Exception {List<Match> matches = new ArrayList<>();List<T> directPathMatches = this.mappingRegistry.getMappingsByDirectPath(exchange);if (directPathMatches != null) {addMatchingMappings(directPathMatches, matches, exchange);}// 省略部分代码if (!matches.isEmpty()) {Comparator<Match> comparator = new MatchComparator(getMappingComparator(exchange));matches.sort(comparator);Match bestMatch = matches.get(0);handleMatch(bestMatch.mapping, bestMatch.getHandlerMethod(), exchange);return bestMatch.getHandlerMethod();}else {return handleNoMatch(this.mappingRegistry.getRegistrations().keySet(), exchange);}
    }
    
执行handler
  1. DispatcherHandler#invokeHandler
    private Mono<HandlerResult> invokeHandler(ServerWebExchange exchange, Object handler) {for (HandlerAdapter handlerAdapter : this.handlerAdapters) {if (handlerAdapter.supports(handler)) {return handlerAdapter.handle(exchange, handler);}}return Mono.error(new IllegalStateException("No HandlerAdapter: " + handler));
    }
    
  2. RequestMappingHandlerAdapter#handle(exchange, handler)
    public Mono<HandlerResult> handle(ServerWebExchange exchange, Object handler) {HandlerMethod handlerMethod = (HandlerMethod) handler;InitBinderBindingContext bindingContext = new InitBinderBindingContext(getWebBindingInitializer(), this.methodResolver.getInitBinderMethods(handlerMethod));InvocableHandlerMethod invocableMethod = this.methodResolver.getRequestMappingMethod(handlerMethod);//Function<Throwable, Mono<HandlerResult>> exceptionHandler =ex -> handleException(ex, handlerMethod, bindingContext, exchange);//return this.modelInitializer.initModel(handlerMethod, bindingContext, exchange).then(Mono.defer(() -> invocableMethod.invoke(exchange, bindingContext))).doOnNext(result -> result.setExceptionHandler(exceptionHandler)).doOnNext(result -> bindingContext.saveModel()).onErrorResume(exceptionHandler);
    }
    
  3. InvocableHandlerMethod#invoke
    public Mono<HandlerResult> invoke(ServerWebExchange exchange, BindingContext bindingContext, Object... providedArgs) {return getMethodArgumentValues(exchange, bindingContext, providedArgs).flatMap(args -> {Object value;Method method = getBridgedMethod();if (KotlinDetector.isSuspendingFunction(method)) {value = CoroutinesUtils.invokeSuspendingFunction(method, getBean(), args);}else {value = method.invoke(getBean(), args);}// 省略部分代码HttpStatus status = getResponseStatus();if (status != null) {exchange.getResponse().setStatusCode(status);}MethodParameter returnType = getReturnType();ReactiveAdapter adapter = this.reactiveAdapterRegistry.getAdapter(returnType.getParameterType());boolean asyncVoid = isAsyncVoidReturnType(returnType, adapter);if ((value == null || asyncVoid) && isResponseHandled(args, exchange)) {return (asyncVoid ? Mono.from(adapter.toPublisher(value)) : Mono.empty());}HandlerResult result = new HandlerResult(this, value, returnType, bindingContext);return Mono.just(result);});
    }
    
处理返回结果
  1. DispatcherHandler#handleResult
    private Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {return getResultHandler(result).handleResult(exchange, result) ;
    }
    
  2. DispatcherHandler#getResultHandler => ResponseBodyResultHandler
  3. ResponseBodyResultHandler#handleResult(exchange, result)
    public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {Object body = result.getReturnValue();MethodParameter bodyTypeParameter = result.getReturnTypeSource();return writeBody(body, bodyTypeParameter, exchange);
    }
    

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/94542.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

移除元素(简单)

优质博文&#xff1a;IT-BLOG-CN 一、题目 给你一个数组nums和一个值val&#xff0c;你需要"原地"移除所有数值等于val的元素&#xff0c;并返回移除后数组的新长度。不要使用额外的数组空间&#xff0c;你必须仅使用O(1)额外空间并"原地"修改输入数组。元…

【微服务的集成测试】python实现-附ChatGPT解析

1.题目 微服务的集成测试 知识点:深搜 时间限制: 1s 空间限制: 256MB 限定语言:不限 题目描述: 现在有n个容器服务,服务的启动可能有一定的依赖性 (有些服务启动没有依赖)其次服务自身启动加载会消耗一些时间。 给你一个 nxn 的二维矩阵 useTime,其中 useTime[i][i]=10 表示…

阿里云关系型数据库有哪些?RDS云数据库汇总

阿里云RDS关系型数据库大全&#xff0c;关系型数据库包括MySQL版、PolarDB、PostgreSQL、SQL Server和MariaDB等&#xff0c;NoSQL数据库如Redis、Tair、Lindorm和MongoDB&#xff0c;阿里云百科分享阿里云RDS关系型数据库大全&#xff1a; 目录 阿里云RDS关系型数据库大全 …

QT实现TCP服务器客户端的实现

ser&#xff1a; widget.cpp&#xff1a; #include "widget.h" #include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget) {ui->setupUi(this);//实例化一个服务器server new QTcpServer(this);// 此时&#xf…

嵌入式软件架构中抽象层设计方法

大家好&#xff0c;今天分享一篇嵌入式软件架构设计相关的文章。 软件架构这东西&#xff0c;众说纷纭&#xff0c;各有观点。什么是软件架构&#xff0c;我们能在网上找到无数种定义。 比如&#xff0c;我们可以这样定义&#xff1a;软件架构是软件系统的基本结构&#xff0c…

g(x)=abx形式的函数最小二乘法计算方法

设函数&#xff0c;利用最小二乘法求解系数a和b: 设&#xff0c;&#xff0c;有 用最小二乘法求解和后&#xff0c;可得和&#xff1a; &#xff0c;

【网络安全---ICMP报文分析】Wireshark教程----Wireshark 分析ICMP报文数据试验

一&#xff0c;试验环境搭建 1-1 试验环境示例图 1-2 环境准备 两台kali主机&#xff08;虚拟机&#xff09; kali2022 192.168.220.129/24 kali2022 192.168.220.3/27 1-2-1 网关配置&#xff1a; 编辑-------- 虚拟网路编辑器 更改设置进来以后 &#xff0c;先选择N…

用pyinstaller打包LGBM模型为ELF/EXE可执行文件

1. 引入 写好的python代码和模型&#xff0c;如果需要做到离线部署、运行&#xff0c;就必须要将代码和模型打包为可独立运行的可执行文件。 使用pyinstaller就能做到这个&#xff0c;相同的代码&#xff0c;在windows上运行就能打包为exe&#xff0c;在linux上运行就能打包为…

android studio导入android源码模块开发总结

一、aidegen自动生成并导入android模块 1.源码下载后&#xff0c;键入 . build/envsetup.sh lunch sdk_car_x86_64-userdebug 以上命令执行后&#xff0c;tools/asuite/aidegen的源码会被编译为aidegen可执行文件 2.使用aidegen生成并自动导入模块 aidegen Settings -i j -…

AJAX和JSON

1、AJAX&#xff1a; AJAX&#xff08;Asynchronous JavaScript and XML&#xff09;是一种用于创建交互式、动态网页的技术。它允许网页在不重新加载整个页面的情况下与服务器进行异步通信&#xff0c;从而改善用户体验。以下是关于AJAX的一些重要信息&#xff1a; 异步通信&a…

银行业务队列简单模拟(队列应用)

设某银行有A、B两个业务窗口&#xff0c;且处理业务的速度不一样&#xff0c;其中A窗口处理速度是B窗口的2倍 —— 即当A窗口每处理完2个顾客时&#xff0c;B窗口处理完1个顾客。给定到达银行的顾客序列&#xff0c;请按业务完成的顺序输出顾客序列。假定不考虑顾客先后到达的时…

虚拟货币(也称为加密货币或数字货币)的运作

虚拟币发展史 虚拟币的发展史可以追溯到20世纪末和21世纪初&#xff0c;以下是虚拟币的重要发展节点&#xff1a; 1998年&#xff1a;比特币白皮书的发布 比特币的概念最早由中本聪&#xff08;Satoshi Nakamoto&#xff09;在1998年提出&#xff0c;随后在2008年发布了一份名…

(Note)机器学习面试题

机器学习 1.两位同事从上海出发前往深圳出差&#xff0c;他们在不同时间出发&#xff0c;搭乘的交通工具也不同&#xff0c;能准确描述两者“上海到深圳”距离差别的是&#xff1a; A.欧式距离 B.余弦距离 C.曼哈顿距离 D.切比雪夫距离 S:D 1. 欧几里得距离 计算公式&#x…

JavaScript事件之拖拽事件(详解)

在网页开发的过程中我们经常会接触到拖拽事件&#xff0c;虽然每个网页和每个网页的拖拽的效果大相径庭&#xff0c;但是从根本来讲&#xff0c;代码是几乎一模一样的。   简而言之&#xff0c;拖拽效果就是鼠标按下&#xff0c;被拖拽的元素随着鼠标而移动&#xff0c;鼠标松…

【单片机】13-实时时钟DS1302

1.RTC的简介 1.什么是实时时钟&#xff08;RTC&#xff09; &#xff08;rtc for real time clock) &#xff08;1&#xff09;时间点和时间段的概念区分 &#xff08;2&#xff09;单片机为什么需要时间点【一定的时间点干什么事情】 &#xff08;3&#xff09;RTC如何存在于…

Trie字符串统计(c++题解)

维护一个字符串集合&#xff0c;支持两种操作&#xff1a; I x 向集合中插入一个字符串 x&#xff1b;Q x 询问一个字符串在集合中出现了多少次。 共有 N 个操作&#xff0c;所有输入的字符串总长度不超过 105&#xff0c;字符串仅包含小写英文字母。 输入格式 第一行包含整…

Mydb数据库问题

1、请简要介绍一下这个基于 Java 的简易数据库管理系统。它的主要功能是什么&#xff1f; TM&#xff08;Transaction Manager&#xff09;&#xff1a;事务管理器&#xff0c;用于维护事务的状态&#xff0c;并提供接口供其他模块查询某个事务的状态。DM&#xff08;Data Man…

国庆假期day5

作业&#xff1a;请写出七层模型及每一层的功能&#xff0c;请绘制三次握手四次挥手的流程图 1.OSI七层模型&#xff1a; 应用层--------提供函 表示层--------表密缩 会话层--------会话 传输层--------进程的接收和发送 网络层--------寻主机 数据链路层----相邻节点的可靠传…

CAcUiDockControlBar初始位置 2023/8/19 下午3:51:18

2023/8/19 下午3:51:18 CAcUiDockControlBar初始位置 2023/8/19 下午3:52:00 CAcUiDockControlBar的初始位置是根据其在程序代码中的设置而确定的。通常情况下,它的初始位置可以通过以下几种方式进行设置: 使用Create函数:在创建CAcUiDockControlBar对象时,可以调用Cre…

2023/8/12 下午8:41:46 树状控件guilite

2023/8/12 下午8:41:46 树状控件guilite 2023/8/12 下午8:42:08 树状控件(Tree View)是一种常见的图形用户界面(GUI)元素,它通常用于显示层次结构数据或文件系统的目录结构。Guilite 是一个轻量级的跨平台 GUI 库,支持多种控件,包括树状控件。 在 Guilite 中使用树状…