合作机构:阿里云 / 腾讯云 / 亚马逊云 / DreamHost / NameSilo / INWX / GODADDY / 百度统计
RabbitMQ是一个开源的消息队列中间件,基于AMQP(Advanced Message Queuing Protocol)协议。它具有高度的可靠性、可扩展性和灵活性,广泛应用于分布式系统中。
特性:
使用方法:
首先需要安装RabbitMQ服务器,并启动它。然后可以使用Java或C#等编程语言通过RabbitMQ的客户端库来发送和接收消息。
示例代码(Java):
// 发送消息
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
String queueName = "hello";
channel.queueDeclare(queueName, false, false, false, null);
String message = "Hello, RabbitMQ!";
channel.basicPublish("", queueName, null, message.getBytes());
System.out.println("Sent message: " + message);
}
// 接收消息
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
String queueName = "hello";
channel.queueDeclare(queueName, false, false, false, null);
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("Received message: " + message);
}
};
channel.basicConsume(queueName, true, consumer);
}
TOP