下面是一个使用公共连接方法调用发送消息到 RabbitMQ 的示例:
- import com.rabbitmq.client.Channel;
- import com.rabbitmq.client.Connection;
- import com.rabbitmq.client.ConnectionFactory;
- import java.io.IOException;
- public class RabbitMQSender {
- private static final String QUEUE_NAME = "hello";
- private static final String EXCHANGE_NAME = "my_exchange";
- private static final String ROUTING_KEY = "my_routing_key";
- private static Connection connection;
- public static void main(String[] args) throws Exception {
- try {
- // 创建连接
- createConnection();
- // 创建通道
- Channel channel = connection.createChannel();
- // 发送消息
- sendMessage(channel, "Hello RabbitMQ!");
- // 关闭通道
- channel.close();
- } finally {
- // 关闭连接
- closeConnection();
- }
- }
- private static void createConnection() throws IOException {
- // 创建连接工厂
- ConnectionFactory factory = new ConnectionFactory();
- factory.setHost("localhost");
- factory.setUsername("guest");
- factory.setPassword("guest");
- // 创建连接
- connection = factory.newConnection();
- }
- private static void closeConnection() throws IOException {
- if (connection != null && connection.isOpen()) {
- connection.close();
- }
- }
- private static void sendMessage(Channel channel, String message) throws IOException {
- // 声明交换机
- channel.exchangeDeclare(EXCHANGE_NAME, "direct");
- // 声明队列
- channel.queueDeclare(QUEUE_NAME, false, false, false, null);
- // 绑定队列到交换机
- channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);
- // 发布消息到交换机
- channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, null, message.getBytes("UTF-8"));
- System.out.println("Sent: " + message);
- }
- }
在上面的示例中,我们创建了一个 createConnection 方法用于创建连接,并在 main 方法中调用。然后,我们在 sendMessage 方法中发送消息到 RabbitMQ,并在 finally 块中调用 closeConnection 方法来关闭连接。
这样可以确保在发送消息结束后关闭连接,防止资源泄漏和连接问题,并提供了一个可重用的公共连接方法。
"小礼物走一走,来肥宅自学平台支持我"
评论区
共条评论
- 这篇文章还没有收到评论,赶紧来抢沙发吧~
首页上页1下页尾页