天天看点

[转] 公司使用SpringMVC的RESTful接口的坑

这边文章的根源可以理解成spring是何如路径解析的

背景:在公司还没有服务化的时候,在整个db层上架构了一个系统作为数据访问层(封装业务系统对数据层的调用,实现对数据库的分库分表,实现对数据的缓存)对外提供的是restful接口

restful:

客户端请求: get /list/cityid/1

非restful

客户端请求: get /list/cityid?cityid=1

在接口越来越多的情况下,系统的性能在降低

[转] 公司使用SpringMVC的RESTful接口的坑
[转] 公司使用SpringMVC的RESTful接口的坑

从结果上可以看出,url的数量越多,springmvc的性能越差,查看源码,依然从dispatcherservlet#dodispatch方法入手

(1)abstracthandlermapping #gethandler

(2)abstracthandlermethodmapping #gethandlerinternal

(3)abstracthandlermethodmapping #lookuphandlermethod

springmvc首先对http请求中的path与已注册的requestmappinginfo(经解析的@requestmapping)中的path进行一个完全匹配来查找对应的handlermethod,即处理该请求的方法,这个匹配就是一个map#get方法。若找不到则会遍历所有的requestmappinginfo进行查找。这个查找是不会提前停止的,直到遍历完全部的requestmappinginfo

springmvc的匹配逻辑:

comparator comparator = new matchcomparator(getmappingcomparator(request))

string match = getmatchingpattern(pattern, lookuppath);

path的匹配首先会把url按照“/”分割,然后对于每一部分都会使用到正则表达式,即使该字符串是定长的静态的。所以该匹配逻辑的性能可能会很差

至于解决方案,公司的文章里面有写到,我正好趁这次机会把原理重新熟悉了一遍