从零到一:Spring Boot 与 RocketMQ 的完美集成指南
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RocketMQProducer {
private final DefaultMQProducer producer;
@Autowired
public RocketMQProducer(DefaultMQProducer producer) {
this.producer = producer;
}
@RequestMapping("/sendMessage")
public String sendMessage() throws Exception {
Message message = new Message("YourTopic", "YourTag", "YourMessageBody".getBytes());
SendResult sendResult = producer.send(message);
return "Message ID: " + sendResult.getMsgId() + ", Send Status: " + sendResult.getSendStatus();
}
}
这段代码展示了如何在Spring Boot应用中使用RocketMQ的producer发送消息。首先,通过@Autowired
注解将配置好的DefaultMQProducer
注入到RocketMQProducer
类中。然后,通过一个简单的sendMessage
方法,我们创建了一个消息对象,并调用producer.send
方法来发送这个消息。最后,我们返回消息ID和发送状态。这个例子展示了如何将RocketMQ的API集成到Spring Boot项目中,并简化了开发者的使用难度。
评论已关闭