RocketMQTemplate是RocketMQ集成到Spring cloud之後提供的個方便發送消息的模板類,它是基本Spring 的消息機制實現的,對外只提供了Spring抽象出來的消息發送接口。在單獨使用RocketMQ的時候,發送消息使用的Message是‘org.apache.rocketmq.common.message’包下面的Message,而使用RocketMQTemplate發送消息時,使用的Message是org.springframework.messaging
的Message,猛一看,沒辦法發送帶tags的消息了,其實在RocketMQ集成的時候已經解決了這個問題。
在RocketMQTemplate發送消息時,調用的方法是:
public SendResult syncSendOrderly(String destination, Message<?> message, String hashKey, long timeout) {
if (Objects.isNull(message) || Objects.isNull(message.getPayload())) {
log.error("syncSendOrderly failed. destination:{}, message is null ", destination);
throw new IllegalArgumentException("`message` and `message.payload` cannot be null");
}
try {
long now = System.currentTimeMillis();
//在這裏對消息進行了轉化,將Spring的message轉化爲rocketmq自己的message
org.apache.rocketmq.common.message.Message rocketMsg = RocketMQUtil.convertToRocketMessage(objectMapper,
charset, destination, message);
SendResult sendResult = producer.send(rocketMsg, messageQueueSelector, hashKey, timeout);
long costTime = System.currentTimeMillis() - now;
log.debug("send message cost: {} ms, msgId:{}", costTime, sendResult.getMsgId());
return sendResult;
} catch (Exception e) {
log.error("syncSendOrderly failed. destination:{}, message:{} ", destination, message);
throw new MessagingException(e.getMessage(), e);
}
}
在上面的代碼中,對消息進行了轉化,將Spring的message轉化爲rocketmq自己的message,在RocketMQUtil.convertToRocketMessage方法中有個地方就是獲取tags的:
String[] tempArr = destination.split(":", 2);
String topic = tempArr[0];
String tags = "";
if (tempArr.length > 1) {
tags = tempArr[1];
}
所以,在發送消息的時候,我們只要把tags使用":"添加到topic後面就可以了。例如:xxxx:tag1 || tag2 || tag3