rabbitMQ是一個在AMQP基礎上完整的,可服用的企業消息系統。他遵循Mozilla Public License 開源協議。
關於amqp可參考http://www.oschina.net/p/rabbitmq/
rabbitmq是一個消費的代理;通過生產者客戶端生產一個信息,轉送給消費者客戶端;在這個傳輸過程中,根據你的需要可以經過路由、緩衝、持久化來得到這個消息。
先通過一個例子開始:通過rabbitmq輸出"Hello World!"
其中P代表生產者、C表示消費者、中間紅色部分代表消息隊列
生產者客戶端的發送消息程序如下:
- package com.abin.test;
- import java.io.IOException;
- import com.rabbitmq.client.Channel;
- import com.rabbitmq.client.Connection;
- import com.rabbitmq.client.ConnectionFactory;
- public class Send {
- private final static String QUEUE_NAME = "hello";
- public static void main(String[] args) throws IOException {
- 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());
- System.out.println(" [x] Sent '" + message + "'");
- channel.close();
- connection.close();
- }
- }
運行結果如下:
- [x] Sent 'Hello World!'
消費者客戶端接收消息程序如下:
- package com.abin.test;
- import com.rabbitmq.client.Channel;
- import com.rabbitmq.client.Connection;
- import com.rabbitmq.client.ConnectionFactory;
- import com.rabbitmq.client.QueueingConsumer;
- public class Reqv {
- private final static String QUEUE_NAME = "hello";
- public static void main(String[] argv) 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);
- System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
- QueueingConsumer consumer = new QueueingConsumer(channel);
- channel.basicConsume(QUEUE_NAME, true, consumer);
- while (true) {
- QueueingConsumer.Delivery delivery = consumer.nextDelivery();
- String message = new String(delivery.getBody());
- System.out.println(" [x] Received '" + message + "'");
- }
- }
- }
運行程序得到的結果如下:
- [*] Waiting for messages. To exit press CTRL+C
- [x] Received 'Hello World!'
如果消費者出現“[x] Received 'Hello World!'”說明已接收到此消息信息。