1. 程式人生 > >rabbitMQ學習筆記(二) 簡單的傳送與接收訊息 HelloWorld

rabbitMQ學習筆記(二) 簡單的傳送與接收訊息 HelloWorld

首先要下載rabbitmq的javaClient庫,然後加入到專案中,下載地址為:http://www.rabbitmq.com/releases/rabbitmq-java-client/v3.1.5/rabbitmq-java-client-bin-3.1.5.zip

1、傳送訊息

傳送訊息首先要獲取與rabbitmq-server的連線,然後從渠道(chann)中指定的queue傳送訊息 , 不能定義兩個queue名字相同,但屬性不同

示例:

Sender01.java

package com.zf.rabbitmq01;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * 傳送訊息
 * @author zhoufeng
 *
 */
public class Sender01 {
	
	public static void main(String[] args) throws IOException {
		
		ConnectionFactory connFac = new ConnectionFactory() ;
		
		//RabbitMQ-Server安裝在本機,所以直接用127.0.0.1
		connFac.setHost("127.0.0.1");
		
		//建立一個連線
		Connection conn = connFac.newConnection() ;
		
		//建立一個渠道
		Channel channel = conn.createChannel() ;
		
		//定義Queue名稱
		String queueName = "queue01" ;
		
		//為channel定義queue的屬性,queueName為Queue名稱
		channel.queueDeclare( queueName , false, false, false, null) ;
		
		String msg = "Hello World!";
		
		//傳送訊息
		channel.basicPublish("", queueName , null , msg.getBytes());
		
		System.out.println("send message[" + msg + "] to "+ queueName +" success!");
		
		channel.close(); 
		conn.close(); 
		
	}

}


Recv01.java

package com.zf.rabbitmq01;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
import com.rabbitmq.client.ShutdownSignalException;

/**
 * 接收訊息
 * @author zhoufeng
 *
 */
public class Recv01 {

	public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
		
		ConnectionFactory connFac = new ConnectionFactory() ;
		
		connFac.setHost("127.0.0.1");
		
		Connection conn = connFac.newConnection() ;
		
		Channel channel = conn.createChannel() ;
		
		String queueName = "queue01";
		
		channel.queueDeclare(queueName, false, false, false, null) ;
		
		//上面的部分,與Sender01是一樣的
		
		//配置好獲取訊息的方式
		QueueingConsumer consumer = new QueueingConsumer(channel) ;
		channel.basicConsume(queueName, true, consumer) ;
		
		//迴圈獲取訊息
		while(true){
			
			//獲取訊息,如果沒有訊息,這一步將會一直阻塞
			Delivery delivery = consumer.nextDelivery() ;
			
			String msg = new String(delivery.getBody()) ;  
			
			System.out.println("received message[" + msg + "] from " + queueName);
		}
		
	}
	
}




此時,無論先後啟動哪個類  ,都沒有關係 ,如果執行Sender01時  Recv01還沒有啟動 , 那麼訊息將被儲存在RabbitMQ-Server上面,直到Recv01啟動後獲取,才會被移除