Rabbitmq的helloworld

1、在linux機器上安裝rabbitmq,並啓動服務:
這裏寫圖片描述
2、下載MQ 客戶端jar包:amqp-client-3.5.4.jar
3、通過rabbitmq輸出”Hello World!”

這裏寫圖片描述

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

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

package com.mq;

import java.io.IOException;  
import java.util.concurrent.TimeoutException;

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 {  
        try {
        ConnectionFactory factory = new ConnectionFactory();  
        factory.setHost("192.168.11.32");  
        Connection connection;

            connection = factory.newConnection();

        Channel channel = connection.createChannel();  

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);  
        String message = "Hello World!";  
        for(int i=0;i<10;i++){
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());  
        System.out.println(" [x] Sent '" + message + "'");  
        }

        channel.close();  
        connection.close(); 
        } catch (TimeoutException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
    }  
}

運行給過如下:

 [x] Sent 'Hello World!'
 [x] Sent 'Hello World!'
 [x] Sent 'Hello World!'
 [x] Sent 'Hello World!'
 [x] Sent 'Hello World!'
 [x] Sent 'Hello World!'

這裏寫圖片描述
5、消費者客戶端接收消息程序如下:

package com.mq;


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("192.168.11.32");  
      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!'
 [x] Received 'Hello World!'
 [x] Received 'Hello World!'
 [x] Received 'Hello World!'
 [x] Received 'Hello World!'
 [x] Received 'Hello World!'
 [x] Received 'Hello World!'

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

發佈了33 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章