首先要下载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
1 package com.zf.rabbitmq01; 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 /** 10 * 发送消息 11 * @author zhoufeng 12 * 13 */ 14 public class Sender01 { 15 16 public static void main(String[] args) throws IOException { 17 18 ConnectionFactory connFac = new ConnectionFactory() ; 19 20 //RabbitMQ-Server安装在本机,所以直接用127.0.0.1 21 connFac.setHost("127.0.0.1"); 22 23 //创建一个连接 24 Connection conn = connFac.newConnection() ; 25 26 //创建一个渠道 27 Channel channel = conn.createChannel() ; 28 29 //定义Queue名称 30 String queueName = "queue01" ; 31 32 //为channel定义queue的属性,queueName为Queue名称 33 channel.queueDeclare( queueName , false, false, false, null) ; 34 35 String msg = "Hello World!"; 36 37 //发送消息 38 channel.basicPublish("", queueName , null , msg.getBytes()); 39 40 System.out.println("send message[" + msg + "] to "+ queueName +" success!"); 41 42 channel.close(); 43 conn.close(); 44 45 } 46 47 }
Recv01.java
1 package com.zf.rabbitmq01; 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 import com.rabbitmq.client.ConsumerCancelledException; 9 import com.rabbitmq.client.QueueingConsumer; 10 import com.rabbitmq.client.QueueingConsumer.Delivery; 11 import com.rabbitmq.client.ShutdownSignalException; 12 13 /** 14 * 接收消息 15 * @author zhoufeng 16 * 17 */ 18 public class Recv01 { 19 20 public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException { 21 22 ConnectionFactory connFac = new ConnectionFactory() ; 23 24 connFac.setHost("127.0.0.1"); 25 26 Connection conn = connFac.newConnection() ; 27 28 Channel channel = conn.createChannel() ; 29 30 String queueName = "queue01"; 31 32 channel.queueDeclare(queueName, false, false, false, null) ; 33 34 //上面的部分,与Sender01是一样的 35 36 //配置好获取消息的方式 37 QueueingConsumer consumer = new QueueingConsumer(channel) ; 38 channel.basicConsume(queueName, true, consumer) ; 39 40 //循环获取消息 41 while(true){ 42 43 //获取消息,如果没有消息,这一步将会一直阻塞 44 Delivery delivery = consumer.nextDelivery() ; 45 46 String msg = new String(delivery.getBody()) ; 47 48 System.out.println("received message[" + msg + "] from " + queueName); 49 } 50 51 } 52 53 }
此时,无论先后启动哪个类 ,都没有关系 ,如果执行Sender01时 Recv01还没有启动 , 那么消息将被保存在RabbitMQ-Server上面,直到Recv01启动后获取,才会被移除