在聊天项目中,需要将消息异步保存到同步到数据库和ES文档中,而ES的mapping中包含了私聊和群聊两种消息模块。现在需要ES的消费组同时订阅私聊和群聊的topic,并都转为ES的消息文档格式并保存。
@Component
@RocketMQMessageListener(consumerGroup = MsgConstant.MSG_ES_SAVE_TOPIC, topic = "")
public class ESMessageListener implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {
@Autowired
private MessageRepository messageRepository;
@Override
public void onMessage(MessageExt messageExt) {
}
@Override
public void prepareStart(DefaultMQPushConsumer consumer) {
try {
consumer.subscribe(MsgConstant.MSG_SAVE_TOPIC, "*");
consumer.subscribe(MsgConstant.GROUP_MSG_SAVE_TOPIC, "*");
consumer.registerMessageListener((List<MessageExt> messages, ConsumeConcurrentlyContext context) -> {
if (CollectionUtils.isNotEmpty(messages)) {
for (MessageExt message : messages) {
String topic = message.getTopic();
MqMsgToESMsg resolver = MqMsgToESMsgContent.getResolver(topic);
MessageEntity messageEntity = new MessageEntity();
MessageEntity convert = resolver.convert(message, messageEntity);
messageRepository.save(convert);
}
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
});
} catch (MQClientException e) {
throw new RuntimeException(e);
}
}
}