以下是Java编程RabbitMQ实现消息的收发的完整攻略,包含两个示例说明。
示例1:发送消息
步骤1:添加依赖
在使用Java编程实现RabbitMQ时,您需要添加以下依赖:
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.12.0</version>
</dependency>
步骤2:创建连接
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Sender {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println("Sent message: " + message);
}
}
}
步骤3:运行程序
运行程序后,您将看到以下输出:
Sent message: Hello World!
示例2:接收消息
步骤1:添加依赖
同示例1。
步骤2:创建连接
import com.rabbitmq.client.*;
import java.io.IOException;
public class Receiver {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println("Waiting for messages...");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println("Received message: " + message);
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
步骤3:运行程序
运行程序后,您将看到以下输出:
Waiting for messages...
Received message: Hello World!
以上就是Java编程RabbitMQ实现消息的收发的完整攻略,包含两个示例说明。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java编程rabbitMQ实现消息的收发 - Python技术站