java访问rabbitMQ队列教程二
java访问rabbitMQ队列教程二,该节主要讲解利用Java来获取在rabbitMQ中的消息对象。
发送消息的代码如下:
代码 |
/**
*
*/
package com.rabbitMQ.pro;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
/**
* @filename Send.java
* @author code by jianghuiwen
* @mail jianghuiwen2012@163.com
*
* 上午8:57:08
*/
public class Send {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv)
throws java.io.IOException {
/*使用工厂类建立Connection和Channel,并且设置参数*/
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.10.86");//MQ的IP
factory.setPort(5672);//MQ端口
factory.setUsername("hfc");//MQ用户名
factory.setPassword("hfc");//MQ密码
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
/*创建消息队列,并且发送消息*/
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
for(int i=0;i<5;i++)
{
String message = String.valueOf(i);
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
}
/*关闭连接*/
channel.close();
connection.close();
}
}
接收代码如下:
代码 |
/**
*
*/
package com.rabbitMQ.pro;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
/**
* @filename Recv.java
* @author code by jianghuiwen
* @mail jianghuiwen2012@163.com
*
* 上午9:17:52
*/
public class Recv {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv)
throws java.io.IOException,
java.lang.InterruptedException {
/*建立连接*/
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.10.86");//MQ的IP
factory.setPort(5672);//MQ端口
factory.setUsername("hfc");//MQ用户名
factory.setPassword("hfc");//MQ密码
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 + "'");
}
}
}
输出结果:
其中四个数字是已经发送到消息队列的消息,我们可以看到,已经能够成功的获取数据。