java中使用rabbitmq
在Java中使用RabbitMQ,你需要依赖RabbitMQ提供的Java客户端库。以下是一个简单的例子,展示了如何在Java中发送和接收消息。
首先,添加Maven依赖到你的项目中:
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.13.0</version>
</dependency>
以下是一个简单的生产者代码示例:
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
public class Send {
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(" [x] Sent '" + message + "'");
}
}
}
以下是一个简单的消费者代码示例:
import com.rabbitmq.client.*;
public class Recv {
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);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
// 创建队列消费者
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + message + "'");
}
};
// 监听队列,Auto-ack = true
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}
}
确保RabbitMQ服务器正在运行,然后先运行Send
类发送消息,接着运行Recv
类接收消息。
评论已关闭