消息類型
•Map•String(含json字元串類型)
處理方法
Map消息

如果發送的消息類型是map類型,可以通過SerializationUtils.deserialize方法将消息轉換成map類型。
字元串類型(含json格式)
預設情況下RabbitMQ發送的消息是為位元組碼,有時我們需要發送JSON格式的消息,則有如下兩種處理方式。
手動轉換成json
@Autowired
private ObjectMapper objectMapper;
public void sendOrder(Order order) {
try {
String orderJson = objectMapper.writeValueAsString(order);
Message message = MessageBuilder
.withBody(orderJson.getBytes())
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
.build();
this.rabbitTemplate.convertAndSend(RabbitConfig.QUEUE_ORDERS, message);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
但是在每一個發送消息的地方都這樣寫就會很繁瑣。
使用MessageConvert自動轉換為json
如果規定了消息的格式為JSON,并使用消息轉換器,則會自動将消息轉化為json格式而不需要每次手動進行轉換。RabbitTemplate預設使用SimpleMessageConverter作為自己的消息轉化器,而SimpleMessageConverter并不能滿足json消息的需求。我們可以使用Jackson2JsonMessageConverter作為預設的消息轉換器。
為RabbitTemplate配置MessageConverter:
@Configuration
public class RabbitConfig {
@Bean
public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory) {
final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(jsonMessageConverter());
return rabbitTemplate;
}
@Bean
public Jackson2JsonMessageConverter jsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
}
通過String類的構造函數接收byte[]類型的消息資料,獲得jsonStr後可以轉換成其它類,然後再進行相關操作。
這裡@RabbitListener注解在方法上,如果類中有多個@RabbitListener(queues = TopicRabbitmqConfig.EVENT_MSG_QUEUE_NAME)注解的方法,測試的結果是輪流的調用。
另一種接收方式
注意,這裡RabbitListener注解在類上,方法中通過@RabbitHandler注解辨別。
控制台
打開 RabbitMQ web 控制台,也可以看到剛才我們在代碼裡面配置的交換器和隊列,以及綁定資訊。
檢視交換器的詳情
檢視隊列