写一个消息队列示例代码
时间: 2023-08-03 22:31:47 浏览: 34
好的,以下是一个使用 RabbitMQ 实现消息队列的示例代码:
首先需要引入 RabbitMQ 的依赖包,例如 Maven:
```xml
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.9.0</version>
</dependency>
```
然后,创建一个生产者发送消息:
```java
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Producer {
private static final String QUEUE_NAME = "hello";
public static void main(String[] args) 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);
// 发送消息
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
System.out.println("Producer send message: " + message);
// 关闭通道和连接
channel.close();
connection.close();
}
}
```
接着,创建一个消费者获取消息:
```java
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer {
private static final String QUEUE_NAME = "hello";
public static void main(String[] args) 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);
// 创建消费者
DefaultConsumer 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("Consumer receive message: " + message);
}
};
// 监听队列
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}
```
这个示例代码中,生产者向名为 "hello" 的队列中发送了一条消息,消费者监听这个队列并从中获取消息并输出。