spring原始碼分析之spring-messaging模組詳解
0 概述
spring-messaging模組為整合messaging api和訊息協議提供支援。
其程式碼結構為:
其中base定義了訊息Message(MessageHeader和body)、訊息處理MessageHandler、傳送訊息MessageChannel。
1. base模組
其結構如下所示:
其中:
message由兩部分組成,
MessageHandler是一個處理訊息的約定,spring messaging提供了豐富的訊息處理方式。
MessageChannel表現為pipes-and-filters架構的管道。
2. 轉換器converter模組
對訊息轉換提供支援。其結構如下:
從上圖可以看出,有訊息到string、json、byte陣列之間的相互轉換。
3. 核心core模組
核心模組提供訊息的模板方法,其結構如下:
4. 處理handler模組
大致架構如下:
其中,
HandlerMethod封裝了一個bean的方法相關資訊(getMethod()和getBean()方法),提供了訪問方法引數的便利工具。HandlerMethod可以在bean factory中使用createWithResolvedBean獲取bean例項時獲取該例項。
MessageCondition是一個將conditions對映到message的約定。
HandlerMethodArgumentResolver 是一個解析方法引數到Context中指定Message的引數值的策略介面。
HandlerMethodReturnValueHandler是一個處理從觸發一個Message的method Handling返回值的策略介面。
另外,也提供了部分註解:
@interface Header:Annotation which indicates that a method parameter should be bound to a message header.
@interface Headers:Annotation which indicates that a method parameter should be bound to the headers of a message. The annotated parameter must be assignable to {@link java.util.Map} with String keys and Object values.
@interface MessageExceptionHandler: Annotation for handling exceptions thrown from message-handling methods within a specific handler class.
@interface MessageMapping:Annotation for mapping a {@link Message} onto message-handling methods by matching to the message destination.
@interface Payload:Annotation that binds a method parameter to the payload of a message. The payload may be passed through a {@link MessageConverter} to convert it from serialized form with specific MIME type to an Object matching the target method parameter.
@interface SendTo:Annotation that indicates a method's return value should be converted to a {@link Message} and sent to the specified destination.
5.Simp模組
包含諸如STOMP協議的簡單訊息協議的通用支援。
STOMP,Streaming Text Orientated Message Protocol,是流文字定向訊息協議,是一種為MOM(Message Oriented Middleware,面向訊息的中介軟體)設計的簡單文字協議。它提供了一個可互操作的連線格式,允許STOMP客戶端與任意STOMP訊息代理(Broker)進行互動,類似於OpenWire(一種二進位制協議)。由於其設計簡單,很容易開發客戶端,因此在多種語言和多種平臺上得到廣泛應用。其中最流行的STOMP訊息代理是Apache ActiveMQ。
詳細協議內容中文版本參見。另stomp架構如下:
(spring 官方圖片)
6. support模組
提供了Message的實現,及建立訊息的MessageBuilder和獲取訊息頭的MessageHeaderAccessor,還有各種不同的MessageChannel實現和channel interceptor支援。
7. tcp模組
一方面提供了通過TcpOperations建立tcp connection、通過TcpConnectionHandler處理訊息和通過TcpConnectionf傳送訊息的抽象及實現;另一方面包含了對基於Reactor的tcp 訊息支援。
8 小結
Spring Framework 4 包含了一個新的spring-messaging
模組,該模組從使用了 Spring Integration 工程的核心概念如 Message
, MessageChannel
,MessageHandler和別的一些可以作為訊息架構的基礎元件。這個模組同樣也提供了一些對映訊息到方法的註解,類似於基於程式設計模型的spring mvc註解。