首先要下载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启动后获取,才会被移除