java rabbitMQ demo

 rabbitMQ是一個在AMQP基礎上完整的,可服用的企業消息系統。他遵循Mozilla Public License 開源協議。

  關於amqp可參考http://www.oschina.net/p/rabbitmq/

 rabbitmq是一個消費的代理;通過生產者客戶端生產一個信息,轉送給消費者客戶端;在這個傳輸過程中,根據你的需要可以經過路由、緩衝、持久化來得到這個消息。

  先通過一個例子開始:通過rabbitmq輸出"Hello World!"

 

 

其中P代表生產者、C表示消費者、中間紅色部分代表消息隊列

 

生產者客戶端的發送消息程序如下:

 

Java代碼  收藏代碼
  1. package com.abin.test;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.rabbitmq.client.Channel;  
  6. import com.rabbitmq.client.Connection;  
  7. import com.rabbitmq.client.ConnectionFactory;  
  8.   
  9. public class Send {  
  10.     private final static String QUEUE_NAME = "hello";  
  11.   
  12.     public static void main(String[] args) throws IOException {  
  13.         ConnectionFactory factory = new ConnectionFactory();  
  14.         factory.setHost("localhost");  
  15.         Connection connection = factory.newConnection();  
  16.         Channel channel = connection.createChannel();  
  17.   
  18.         channel.queueDeclare(QUEUE_NAME, falsefalsefalsenull);  
  19.         String message = "Hello World!";  
  20.         channel.basicPublish("", QUEUE_NAME, null, message.getBytes());  
  21.         System.out.println(" [x] Sent '" + message + "'");  
  22.   
  23.         channel.close();  
  24.         connection.close();  
  25.     }  
  26. }  

運行結果如下:

Java代碼  收藏代碼
  1. [x] Sent 'Hello World!'  

 

消費者客戶端接收消息程序如下:

 

Java代碼  收藏代碼
  1. package com.abin.test;  
  2.   
  3. import com.rabbitmq.client.Channel;  
  4. import com.rabbitmq.client.Connection;  
  5. import com.rabbitmq.client.ConnectionFactory;  
  6. import com.rabbitmq.client.QueueingConsumer;  
  7.   
  8. public class Reqv {  
  9.     private final static String QUEUE_NAME = "hello";  
  10.   
  11.     public static void main(String[] argv) throws Exception {  
  12.   
  13.         ConnectionFactory factory = new ConnectionFactory();  
  14.         factory.setHost("localhost");  
  15.         Connection connection = factory.newConnection();  
  16.         Channel channel = connection.createChannel();  
  17.   
  18.         channel.queueDeclare(QUEUE_NAME, falsefalsefalsenull);  
  19.         System.out.println(" [*] Waiting for messages. To exit press CTRL+C");  
  20.   
  21.         QueueingConsumer consumer = new QueueingConsumer(channel);  
  22.         channel.basicConsume(QUEUE_NAME, true, consumer);  
  23.   
  24.         while (true) {  
  25.             QueueingConsumer.Delivery delivery = consumer.nextDelivery();  
  26.             String message = new String(delivery.getBody());  
  27.             System.out.println(" [x] Received '" + message + "'");  
  28.         }  
  29.     }  
  30. }  

 運行程序得到的結果如下:

Java代碼  收藏代碼
  1. [*] Waiting for messages. To exit press CTRL+C  
  2. [x] Received 'Hello World!'  

 如果消費者出現“[x] Received 'Hello World!'”說明已接收到此消息信息。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章