rabbitmq通过订阅接受消息java代码案例
时间: 2025-06-28 17:16:35 浏览: 6
### RabbitMQ Java Example Code for Subscribing and Receiving Messages
To subscribe and receive messages from RabbitMQ using Java, one can utilize the `com.rabbitmq.client` library which provides necessary classes such as `Channel`, `Connection`, etc., to interact with RabbitMQ server.
Below is an example of how this could be implemented:
```java
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ReceiveMessages {
private final static String QUEUE_NAME = "test_queue";
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");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println("[x] Received '" + message + "'");
// Acknowledge receipt of the message.
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
};
boolean autoAck = false; // Manual acknowledgment mode enabled by setting this flag to false
channel.basicConsume(QUEUE_NAME, autoAck, deliverCallback, consumerTag -> {});
}
}
}
```
This program sets up a queue named `"test_queue"` on localhost RabbitMQ instance[^1]. It listens continuously until interrupted externally while printing out any received messages along with acknowledging them after processing has completed successfully.
阅读全文
相关推荐




















