java rabbitmq 队列代码
时间: 2023-08-28 08:07:55 浏览: 91
rabbitmq 7种队列实现java版
以下是使用Java编写的RabbitMQ队列代码示例:
```java
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class RabbitMQExample {
private final static String QUEUE_NAME = "my_queue";
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setUsername("guest");
factory.setPassword("guest");
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(" [x] Sent '" + message + "'");
channel.close();
connection.close();
}
}
```
这段代码创建了一个连接到RabbitMQ服务器的`Connection`对象和一个`Channel`对象。然后它使用`channel.queueDeclare()`方法声明一个队列。接下来,它将一个消息发送到队列中,使用`channel.basicPublish()`方法。最后,它关闭了`Channel`对象和`Connection`对象。
阅读全文