使用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.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RocketMQProducerController {
private final DefaultMQProducer producer;
@Autowired
public RocketMQProducerController(DefaultMQProducer producer) {
this.producer = producer;
}
@GetMapping("/sendMessage")
public String sendMessage(@RequestParam String topic, @RequestParam String message) {
try {
Message msg = new Message(topic, "TagA", message.getBytes(RemotingHelper.DEFAULT_CHARSET));
SendResult sendResult = producer.send(msg);
return "Message is sent. Result: " + sendResult.getSendStatus();
} catch (Exception e) {
e.printStackTrace();
return "Failed to send the message. Error: " + e.getMessage();
}
}
}
这段代码演示了如何在Spring Boot应用程序中使用已经配置好的RocketMQ生产者来发送消息。当访问/sendMessage
路径时,通过GET请求传递的topic
和message
将被发送至RocketMQ服务器。发送结果会以字符串的形式返回。
评论已关闭