异步发送消息和回调

2021-07-31 消息队列RocketMQSpringBoot中间件

同步消息需要发送消息成功后才可以继续往下执行,然而在一些对响应时间敏感的业务场景,发送端不能容忍长时间地等待Broker的响应,那么此时就需要异步消息了。

核心代码

producer.send(message, new SendCallback(){
	onSuccess(){}
	onException(){}
})

发送异步消息

@RequestMapping("/async")
public String asyncMsg(String text) throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
    // key是唯一的,一般是订单号等,这里仅做测试,生产者根据key进行消息重投,默认次数为2
    Message message = new Message(JmsConfig.TOPIC, "tag1","1234", ("Hello rocketmq = " + text).getBytes());
    payProducer.getProducer().send(message, new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
            System.out.printf("发送结果 %s, msg=%s", sendResult.getSendStatus(), sendResult.toString());
        }

        @Override
        public void onException(Throwable throwable) {
            throwable.printStackTrace();
            //补偿机制,根据业务情况查看是否需要进行重试
        }
    });
    return "";
}
上次更新: 2 年前