我在應用程式 A 和Spring Amqp Library應用程式 B 中使用自定義 RabbitMQ 客戶端。我遇到了一個問題:如何決定@RabbitListener用于不同訊息型別的女巫?
問題:我從應用 A 向應用 B 發送自定義訊息。在訊息中,我設定了自定義標頭“型別”——它不是默認屬性,也不是默認 Spring Amqp 標頭(即“_ _ TypeId _ _”)——只是一個新的自定義標題。
在應用程式 B(spring amqp)中,我必須決定使用哪個監聽器。據我了解,Spring Amqp使用“_ _ TypeId _ _”作為“訊息型別檢測策略”的默認機制(我不知道如何正確呼叫它),但我想使用自己的“策略”。
我找到了下一個技巧,但它似乎很奇怪且不明顯:
private void determineMessageType(Message message) {
MessageProperties props = message.getMessageProperties();
Map<String, Object> headers = props.getHeaders();
final String type = String.valueOf(headers.get("type"));
if ("popularity-report".equals(type)) {
props.getHeaders().put("__TypeId__",
PopularityReportCommand.class.getName());
}
}
我可以以某種方式對 Spring Amqp 應用程式使用自定義型別檢測策略嗎?或者如何在 Spring Amqp 中正確解決這些問題?
uj5u.com熱心網友回復:
提到_ _ TypeId _ _的僅用于 JSON 訊息轉換器。所以,如果這對你來說真的是你從那個制作人那里真正發送的部分,那么你可以看看AbstractJackson2MessageConverter.setJavaTypeMapper(Jackson2JavaTypeMapper). 默認的DefaultJackson2JavaTypeMapper具有這樣的屬性:
public String getClassIdFieldName() {
return DEFAULT_CLASSID_FIELD_NAME;
}
這真的是上面提到的名字:
public static final String DEFAULT_CLASSID_FIELD_NAME = "__TypeId__";
因此,如果您能夠擴展它DefaultJackson2JavaTypeMapper并為您的自定義標頭映射器覆寫該 getter,那么它Jackson2JsonMessageConverter可以正確地將傳入的 JSON 資料轉換為您的自定義標頭呈現的所需型別。然后@RabbitListener會接受這個值。
但是您仍然需要確保typePrecedence在該映射器上設定為TYPE_ID:
/**
* Set the precedence for evaluating type information in message properties.
* When using {@code @RabbitListener} at the method level, the framework attempts
* to determine the target type for payload conversion from the method signature.
* If so, this type is provided in the
* {@link MessageProperties#getInferredArgumentType() inferredArgumentType}
* message property.
* <p>
* By default, if the type is concrete (not abstract, not an interface), this will
* be used ahead of type information provided in the {@code __TypeId__} and
* associated headers provided by the sender.
* <p>
* If you wish to force the use of the {@code __TypeId__} and associated headers
* (such as when the actual type is a subclass of the method argument type),
* set the precedence to {@link Jackson2JavaTypeMapper.TypePrecedence#TYPE_ID}.
*
* @param typePrecedence the precedence.
* @since 1.6
*/
public void setTypePrecedence(TypePrecedence typePrecedence) {
否則,它會咨詢@RabbitListener方法簽名。
在檔案中查看更多資訊:https : //docs.spring.io/spring-amqp/docs/current/reference/html/#Jackson2JsonMessageConverter-from-message
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/409709.html
標籤:
