@PathVariable性能损耗分析
前端时间参与了一次业务线排障,是接口服务并发性能比较差,性能损耗大的问题,我经过几次研究分析和压测,确定了故障源是@PathVariable耗时过长引起的。
@PathVariable使用形式:
@RequestMapping(value = "/api/test/{appCode}/queryUserByUserId", method = RequestMethod.GET)
@ResponseBody
String queryUserByUserId(@PathVariable(name = "appCode") String appCode,@RequestParam("userId") Long userId);
这个注解是Spring MVC提供的,之前没有想到过这个注解会带来性能损耗,为了彻底分析清楚@PathVariable是什么原因导致了性能损耗,于是我对DispatcherServlet.getHandler()这个方法的操作过程进行了仔细地研读,下面我们来对它进行逐步的分析。
首先我把获取handlerMethod的整个流程展示出来,思路会更清晰一些。

我们来对关键代码进行解读分析,
查找路径的过程中的核心代码代码,即流程图中org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod方法
List<Match> matches = new ArrayList<Match>();
List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
if (directPathMatches != null) {
addMatchingMappings(directPathMatches, matches, request);
}
if (matches.isEmpty()) {
// No choice but to go through all mappings...
addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);
}
AbstractHandlerMethodMapping首先对request请求中的lookupPath与已注册的RequestMappingInfo(@RequestMapping注解的方法)中的path进行完全匹配来查找对应的HandlerMethod,即处理该请求的方法,LinkedMultiValueMap#get方法。若没有找到则会遍历所有的RequestMappingInfo进行查找。这个查找是不会提前停止的,直到遍历完全部的RequestMappingInfo;这个查找会进行正则匹配,将请求lookupPath按"/"为分隔符,逐条进行匹配,如果完全匹配,则返回该RequestMappingInfo。
org.springframework.web.servlet.mvc.method.RequestMappingInfo.getMatchingCondition()方法
@Override
public RequestMappingInfo getMatchingCondition(HttpServletRequest request) {
RequestMethodsRequestCondition methods = this.methodsCondition.getMatchingCondition(request);
ParamsRequestCondition params = this.paramsCondition.getMatchingCondition(request);
HeadersRequestCondition headers = this.headersCondition.getMatchingCondition(request);
ConsumesRequestCondition consumes = this.consumesCondition.getMatchingCondition(request);
ProducesRequestCondition produces = this.producesCondition.getMatchingCondition(request); if (methods == null || params == null || headers == null || consumes == null || produces == null) {
return null;
} PatternsRequestCondition patterns = this.patternsCondition.getMatchingCondition(request);
if (patterns == null) {
return null;
} RequestConditionHolder custom = this.customConditionHolder.getMatchingCondition(request);
if (custom == null) {
return null;
} return new RequestMappingInfo(this.name, patterns,
methods, params, headers, consumes, produces, custom.getCondition());
}
在遍历过程中,RequestMappingInfo首先会根据@RequestMapping中的headers, params, produces, consumes, methods与实际的HttpServletRequest中的信息对比,以剔除掉不符合条件的RequestMappingInfo。
如果以上信息都能够匹配上,那么SpringMVC会对RequestMapping中的path进行正则匹配,剔除不能进行匹配的RequestMappingInfo。
遍历完mappingRegistry后
RequestMappingInfo ===> Match(RequestMappingInfo,HandlerMethod) ===>List<Match> matches.add(Match);
Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
Collections.sort(matches, comparator);
接下来会对所有符合条件Match进行评分并排序。最后选择分数最高的那个作为结果。
@Override
public int compareTo(RequestMappingInfo other, HttpServletRequest request) {
int result;
// Automatic vs explicit HTTP HEAD mapping
if (HttpMethod.HEAD.matches(request.getMethod())) {
result = this.methodsCondition.compareTo(other.getMethodsCondition(), request);
if (result != 0) {
return result;
}
}
result = this.patternsCondition.compareTo(other.getPatternsCondition(), request);
if (result != 0) {
return result;
}
result = this.paramsCondition.compareTo(other.getParamsCondition(), request);
if (result != 0) {
return result;
}
result = this.headersCondition.compareTo(other.getHeadersCondition(), request);
if (result != 0) {
return result;
}
result = this.consumesCondition.compareTo(other.getConsumesCondition(), request);
if (result != 0) {
return result;
}
result = this.producesCondition.compareTo(other.getProducesCondition(), request);
if (result != 0) {
return result;
}
// Implicit (no method) vs explicit HTTP method mappings
result = this.methodsCondition.compareTo(other.getMethodsCondition(), request);
if (result != 0) {
return result;
}
result = this.customConditionHolder.compareTo(other.customConditionHolder, request);
if (result != 0) {
return result;
}
return 0;
}
可以看出它的评分优先级
HttpMethod > pathPattern > param > headers > consumes > produces > (Implicit (no method) vs explicit HTTP method) > custom
如果matches有多个,接下来会比较第一个和第二个是否相等,如果compare==0,就会抛出异常了
Match bestMatch = matches.get(0);
if (matches.size() > 1) {
if (CorsUtils.isPreFlightRequest(request)) {
return PREFLIGHT_AMBIGUOUS_MATCH;
}
Match secondBestMatch = matches.get(1);
if (comparator.compare(bestMatch, secondBestMatch) == 0) {
Method m1 = bestMatch.handlerMethod.getMethod();
Method m2 = secondBestMatch.handlerMethod.getMethod();
throw new IllegalStateException("Ambiguous handler methods mapped for HTTP path '" +
request.getRequestURL() + "': {" + m1 + ", " + m2 + "}");
}
}
通过上述的分析可以得出一个结论:在使用非RESTful风格的URL时,SpringMVC可以立刻找到对应的HandlerMethod来处理请求。但是当在URL中存在变量时,即使用了@PathVariable时,SpringMVC就会进行上述的复杂流程,并且每次请求都会走这个复杂的流程。
总结一下:Spring 不仅给我们提供了方便我们使用的框架,更是在此基础上配合提供了各种各样的功能强大的组件,她的伟大是毋庸置疑的,spring 面向大众,尽可能为更多的开发者提供便利,我们在使用spring的时候应该依据自身的实际状况,充分了解要使用的组件,去应用它,这样才能避免走弯路。
@PathVariable性能损耗分析的更多相关文章
- SQL SERVER 查询性能优化——分析事务与锁(五)
SQL SERVER 查询性能优化——分析事务与锁(一) SQL SERVER 查询性能优化——分析事务与锁(二) SQL SERVER 查询性能优化——分析事务与锁(三) 上接SQL SERVER ...
- list 、set 、map 粗浅性能对比分析
list .set .map 粗浅性能对比分析 不知道有多少同学和我一样,工作五年了还没有仔细看过list.set的源码,一直停留在老师教导的:"LinkedList插入性能比Array ...
- Android App性能评测分析-流畅度篇
1.前言 在手机App竞争越来越激烈的今天,Android App的各项性能特别是流畅度不如IOS,安卓基于java虚拟机运行,触控响应的延迟和卡顿比IOS系统严重得多.一些下拉上滑.双指缩放快速打字 ...
- 开源性能监控分析工具glowroot
最近在做java性能瓶颈定位分析工具的研究,发现glowroot工具是一款相当不错的APM工具(Wonderful tool),架构简洁,部署简单,上手容易. 经过亲身搭建体验,总结了产品的架构,工具 ...
- MySQL索引及性能优化分析
一.SQL性能下降的原因 查询语句问题,各种连接.子查询 索引失效(单值索引.复合索引) 服务器调优及各个参数设置(缓冲.线程池等) 二.索引 排好序的快速查找数据结构 1. 索引分类 单值索引 一个 ...
- 浅谈C++之冒泡排序、希尔排序、快速排序、插入排序、堆排序、基数排序性能对比分析之后续补充说明(有图有真相)
如果你觉得我的有些话有点唐突,你不理解可以想看看前一篇<C++之冒泡排序.希尔排序.快速排序.插入排序.堆排序.基数排序性能对比分析>. 这几天闲着没事就写了一篇<C++之冒泡排序. ...
- ArrayList和LinkedList的几种循环遍历方式及性能对比分析
最新最准确内容建议直接访问原文:ArrayList和LinkedList的几种循环遍历方式及性能对比分析 主要介绍ArrayList和LinkedList这两种list的五种循环遍历方式,各种方式的性 ...
- Web服务器性能监控分析与优化
Web服务器性能监控分析与优化 http://www.docin.com/p-759040698.html
- ArrayList和LinkedList遍历方式及性能对比分析
ArrayList和LinkedList的几种循环遍历方式及性能对比分析 主要介绍ArrayList和LinkedList这两种list的五种循环遍历方式,各种方式的性能测试对比,根据ArrayLis ...
随机推荐
- [zz] pomelo windows 环境下开发环境搭建
原文链接:http://nodejs.netease.com/topic/515279a0b5a2705b5a000983 本文主要介绍下 windows 下跑通 pomelo 简单例子的过程 开发前 ...
- vue 辅助开发工具(利用node自动生成相关文件,自动注册路由)
vue 辅助开发工具 前言 有没有因为新建view,component,store的繁琐操作而苦恼,需要新建文件件,新建vue文件,新建js文件,注册路由...等一系列无价值操作浪费时间,为了解决这个 ...
- Redis回顾
之前有两篇文章着重介绍了redis集群的搭建和redis与spring的整合,一个月过去了,现在有些忘记了,今天又拿过来稳固一下,发现有很多的东西都忘记了. 资料汇总下载 首先安装ruby环境 安装过 ...
- CSS实现三栏布局(5种)
常见的布局方式: float布局.Position定位.table布局.弹性(flex)布局.网格(grid)布局 那么我们就是用以上5种方式完成三栏布局,不过前提是左右宽度(假如左右宽度为300px ...
- 面试java后端面经_2
1 自我介绍(介绍一下帅气的自己哦) 2 对象深浅复制(浅复制:对象内引用的对象不会复制,深复制会把引用对象复制.如何进行深浅复制,这块不懂的童鞋可以百度一下) 3 wait方法和sleep方法的区别 ...
- web 上读取图片,并转化为指定格式
一. 转换为 base64 public static string ObtainBase64FromWeb(string domain, string path) { string url = &q ...
- c# oracle 数据库连接以及参数化查询
private string OracleSearchDemo(string cadqueueId) { string address = null; using (OracleConnection ...
- Python 面向導向語言 Object Oriented Programming Language
Pytho 是面向對象的程式語言,舉凡 Literals 值都是 Object.例如: >>> id(38)8791423739696 與 >>> id('ABC' ...
- Go_笔试题记录-不熟悉的
1.golang中没有隐藏的this指针,这句话的含义是() A. 方法施加的对象显式传递,没有被隐藏起来 B. golang沿袭了传统面向对象编程中的诸多概念,比如继承.虚函数和构造函数 C. go ...
- 关于c++中的复合类型
目录 数组 字符串 结构体 共用体 枚举 指针 数和指针的关系 常见的存储方式 数组替代品 一.数组 存储在每个元素中值的类型 数组名 数组中的元素数 通用格式:typename arrayname ...