一、前言
Spring Flux中的核心DispatcherHandler的處理過程分為三步,其中首步就是通過HandlerMapping接口查找Request所對應的Handler。本文就是通過閱讀源碼的方式,分析一下HandlerMapping接口的實作者之一——RequestMappingHandlerMapping類,用于處理基于注解的路由政策,把所有用@Controller和@RequestMapping标記的類中的Handler識别出來,以便DispatcherHandler調用的。
HandlerMapping接口的另外兩種實作類:1、RouterFunctionMapping用于函數式端點的路由;2、SimpleUrlHandlerMapping用于顯式注冊的URL模式與WebHandler配對。
文章系列
- 關于非阻塞IO: 《從時間碎片角度了解阻塞IO模型及非阻塞模型》
- 關于SpringFlux新手入門: 《快速上手Spring Flux架構》
- Spring Flux中Request與HandlerMapping關系的形成過程 本文
二、對基于注解的路由控制器的抽象
Spring中基于注解的控制器的使用方法大緻如下:
@Controller
public class MyHandler{
@RequestMapping("/")
public String handlerMethod(){
}
}
在Spring WebFlux中,對上述使用方式進行了三層抽象模型。
- Mapping
- 使用者定義的基于annotation的映射關系
- 該抽象對應的類是:org.springframework.web.reactive.result.method.RequestMappingInfo
- 比如上述例子中的 @RequestMapping("/")所代表的映射關系
- Handler
- 代表控制器的類
- 該抽象對應的類是:java.lang.Class
- 比如上述例子中的MyHandler類
- Method
- 具體處理映射的方法
- 該抽象對應的類是:java.lang.reflect.Method
- 比如上述例子中的String handlerMethod()方法
- HandlerMethod
- Handler與Method的結合體,Handler(類)與Method(方法)搭配後就成為一個可執行的單元了
- Mapping vs HandlerMethod
- 把Mapping與HandlerMethod作為字典存起來,就可以根據請求中的關鍵資訊(路徑、頭資訊等)來比對到Mapping,再根據Mapping找到HandlerMethod,然後執行HandlerMethod,并傳遞随請求而來的參數。
了解了這個抽象模型後,接下來分析源碼來了解Spring WebFlux如何處理請求與Handler之間的Mapping關系時,就非常容易了。
HandlerMapping接口及其各實作類負責上述模型的建構與運作。
三、HandlerMapping接口實作的設計模式
HandlerMapping接口實作,采用了"模版方法"這種設計模式。
1層:AbstractHandlerMapping implements HandlerMapping, Ordered, BeanNameAware
^
|
2層:AbstractHandlerMethodMapping implements InitializingBean
^
|
3層:RequestMappingInfoHandlerMapping
^
|
4層:RequestMappingHandlerMapping implements EmbeddedValueResolverAware
下面對各層的職責作簡要說明:
- 第1層主要實作了對外提供模型的接口
- 即重載了HandlerMapping接口的"Mono
- 第2層有兩個責任 —— 解析使用者定義的HandlerMethod + 實作對外提供模型接口實作所需的抽象方法
- 通過實作了InitializingBean接口的"void afterPropertiesSet()"方法,解析使用者定義的Handler和Method。
- 實作第1層對外提供模型接口實作所需的抽象方法:"Mono<?> getHandlerInternal(ServerWebExchange exchange)"
- 第3層提供根據請求比對Mapping模型執行個體的方法
- 第4層實作一些高層次用到的抽象方法來建立具體的模型執行個體。
小結一下,就是HandlerMapping接口及其實作類,把使用者定義的各Controller等,抽象為上述的Mapping、Handler及Method模型,并将Mapping與HandlerMethod作為字典關系存起來,還提供通過比對請求來獲得HandlerMethod的公共方法。
接下來的章節,将先分析解析使用者定義的模型并緩存模型的過程,然後再分析一下比對請求來獲得HandlerMethod的公共方法的過程。
四、解析使用者定義的模型并緩存模型的過程
4-1、實作InitializingBean接口
第2層AbstractHandlerMethodMapping抽象類中的一個重要方法——實作了InitializingBean接口的"void afterPropertiesSet()"方法,為Spring WebFlux帶來了解析使用者定義的模型并緩存模型的機會 —— Spring容器初初始化完成該類的具體類的Bean後,将會回調這個方法。
在該方法中,實作擷取使用者定義的Handler、Method、Mapping以及緩存Mapping與HandlerMethod映射關系的功能。
@Override
public void afterPropertiesSet() {
initHandlerMethods();
// Total includes detected mappings + explicit registrations via registerMapping..
...
}
4-2、找到使用者定義的Handler
afterPropertiesSet方法中主要是調用了void initHandlerMethods()方法,具體如下:
protected void initHandlerMethods() {
//擷取Spring容器中所有Bean名字
String[] beanNames = obtainApplicationContext().getBeanNamesForType(Object.class);
for (String beanName : beanNames) {
if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
Class<?> beanType = null;
try {
//擷取Bean的類型
beanType = obtainApplicationContext().getType(beanName);
}
catch (Throwable ex) {
// An unresolvable bean type, probably from a lazy bean - let's ignore it.
if (logger.isTraceEnabled()) {
logger.trace("Could not resolve type for bean '" + beanName + "'", ex);
}
}
//如果擷取到類型,并且類型是Handler,則繼續加載Handler方法。
if (beanType != null && isHandler(beanType)) {
detectHandlerMethods(beanName);
}
}
}
//初始化後收尾工作
handlerMethodsInitialized(getHandlerMethods());
}
這兒首先擷取Spring容器中所有Bean名字,然後循環處理每一個Bean。如果Bean名稱不是以SCOPED_TARGET_NAME_PREFIX常量開頭,則擷取Bean的類型。如果擷取到類型,并且類型是Handler,則繼續加載Handler方法。
isHandler(beanType)調用,檢查Bean的類型是否符合handler定義。
AbstractHandlerMethodMapping抽象類中定義的抽象方法"boolean isHandler(Class<?> beanType)",是由RequestMappingHandlerMapping類實作的。具體實作代碼如下:
protected boolean isHandler(Class<?> beanType) {
return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
}
不難看出,對于RequestMappingHandlerMapping這個實作類來說,隻有擁有@Controller或者@RequestMapping注解的類,才是Handler。(言下之意對于其他實作類來說Handler的定義不同)。
具體handler的定義,在HandlerMapping各實作類來說是不同的,這也是isHandler抽象方法由具體實作類來實作的原因。
4-3、發現Handler的Method
接下來我們要重點看一下"detectHandlerMethods(beanName);"這個方法調用。
protected void detectHandlerMethods(final Object handler) {
Class<?> handlerType = (handler instanceof String ?
obtainApplicationContext().getType((String) handler) : handler.getClass());
if (handlerType != null) {
//将handlerType轉換為使用者類型(通常等同于被轉換的類型,不過諸如CGLIB生成的子類會被轉換為原始類型)
final Class<?> userType = ClassUtils.getUserClass(handlerType);
//尋找目标類型userType中的Methods,selectMethods方法的第二個參數是lambda表達式,即感興趣的方法的過濾規則
Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
//回調函數metadatalookup将通過controller定義的mapping與手動定義的mapping合并起來
(MethodIntrospector.MetadataLookup<T>) method -> getMappingForMethod(method, userType));
if (logger.isTraceEnabled()) {
logger.trace("Mapped " + methods.size() + " handler method(s) for " + userType + ": " + methods);
}
methods.forEach((key, mapping) -> {
//再次核查方法與類型是否比對
Method invocableMethod = AopUtils.selectInvocableMethod(key, userType);
//如果是滿足要求的方法,則注冊到全局的MappingRegistry執行個體裡
registerHandlerMethod(handler, invocableMethod, mapping);
});
}
}
首先将參數handler(即外部傳入的BeanName或者BeanType)轉換為Class<?>類型變量handlerType。如果轉換成功,再将handlerType轉換為使用者類型(通常等同于被轉換的類型,不過諸如CGLIB生成的子類會被轉換為原始類型)。接下來擷取該使用者類型裡所有的方法(Method)。循環處理每個方法,如果是滿足要求的方法,則注冊到全局的MappingRegistry執行個體裡。
4-4、解析Mapping資訊
其中,以下代碼片段有必要深入探究一下
Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
(MethodIntrospector.MetadataLookup<T>) method -> getMappingForMethod(method, userType));
MethodIntrospector.selectMethods方法的調用,将會把用@RequestMapping标記的方法篩選出來,并交給第二個參數所定義的MetadataLookup回調函數将通過controller定義的mapping與手動定義的mapping合并起來。
第二個參數是用lambda表達式傳入的,表達式中将method、userType傳給getMappingForMethod(method, userType)方法。
getMappingForMethod方法在高層次中是抽象方法,具體的是現在第4層RequestMappingHandlerMapping類中實作。在具體實作getMappingForMethod時,會調用到RequestMappingHandlerMapping類的下面這個方法。從該方法中,我們可以看到,首先會獲得參數element(即使用者在Controller中定義的方法)的RequestMapping類型的類執行個體,然後構造代表Mapping抽象模型的RequestmappingInfo類型執行個體并傳回。
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);
}
構造代表Mapping抽象模型的RequestmappingInfo類型執行個體,用的是createRequestMappingInfo方法,如下。可以看到RequestMappingInfo所需要的資訊,包括paths、methods、params、headers、consumers、produces、mappingName,即使用者定義@RequestMapping注解時所設定的可能的參數,都被存在這兒了。擁有了這些資訊,當請求來到時,RequestMappingInfo就可以測試自身是否是處理該請求的人選之一了。
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();
}
4-5、緩存Mapping與HandlerMethod關系
最後,registerHandlerMethod(handler, invocableMethod, mapping)調用将緩存HandlerMethod,其中mapping參數是RequestMappingInfo類型的。。
内部調用的是MappingRegistry執行個體的void register(T mapping, Object handler, Method method)方法,其中T是RequestMappingInfo類型。
MappingRegistry類維護所有指向Handler Methods的映射,并暴露方法用于查找映射,同時提供并發控制。
public void register(T mapping, Object handler, Method method) {
this.readWriteLock.writeLock().lock();
try {
HandlerMethod handlerMethod = createHandlerMethod(handler, method);
......
this.registry.put(mapping, new MappingRegistration<>(mapping, handlerMethod, directUrls, name));
}
finally {
this.readWriteLock.writeLock().unlock();
}
}
五、比對請求來獲得HandlerMethod
AbstractHandlerMethodMapping類的“Mono getHandlerInternal(ServerWebExchange exchange)”方法,具體實作了根據請求查找HandlerMethod的邏輯。
@Override
public Mono<HandlerMethod> getHandlerInternal(ServerWebExchange exchange) {
//擷取讀鎖
this.mappingRegistry.acquireReadLock();
try {
HandlerMethod handlerMethod;
try {
//調用其它方法繼續查找HandlerMethod
handlerMethod = lookupHandlerMethod(exchange);
}
catch (Exception ex) {
return Mono.error(ex);
}
if (handlerMethod != null) {
handlerMethod = handlerMethod.createWithResolvedBean();
}
return Mono.justOrEmpty(handlerMethod);
}
//釋放讀鎖
finally {
this.mappingRegistry.releaseReadLock();
}
}
handlerMethod = lookupHandlerMethod(exchange)調用,繼續查找HandlerMethod。我們繼續看一下HandlerMethod lookupHandlerMethod(ServerWebExchange exchange)方法的定義。為友善閱讀,我把注釋也寫在了代碼裡。
protected HandlerMethod lookupHandlerMethod(ServerWebExchange exchange) throws Exception {
List<Match> matches = new ArrayList<>();
//查找所有滿足請求的Mapping,并放入清單mathes
addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, exchange);
if (!matches.isEmpty()) {
//擷取比較器comparator
Comparator<Match> comparator = new MatchComparator(getMappingComparator(exchange));
//使用比較器将清單matches排序
matches.sort(comparator);
//将排在第1位的作為最佳比對項
Match bestMatch = matches.get(0);
if (matches.size() > 1) {
//将排在第2位的作為次佳比對項
Match secondBestMatch = matches.get(1);
}
handleMatch(bestMatch.mapping, bestMatch.handlerMethod, exchange);
return bestMatch.handlerMethod;
}
else {
return handleNoMatch(this.mappingRegistry.getMappings().keySet(), exchange);
}
}
六、總結
了解了Spring WebFlux在擷取映射關系方面的抽象設計模型後,就很容易讀懂代碼,進而更加了解架構的具體處理方式,在使用架構時做到“知己知彼”。