准备:
1.下载rabbitmq并搭建环境(和python那篇一样:http://www.cnblogs.com/g177w/p/8176797.html)
2.下载支持的jar包(http://repo1.maven.org/maven2/com/rabbitmq/amqp-client)
生产者方(Productor.java):
package RabbitMQTest; import java.util.HashMap;
import java.util.Map; import com.rabbitmq.client.AMQP.Queue;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory; public class Productor {
public static String QUEUE_NAME = "STEVEN";
public static void main(String[] args) {
//初始化socket链接
ConnectionFactory factory = new ConnectionFactory();
//指定链接地址
factory.setHost("localhost");
try{
//建立程序和rabbitmq的socket连接
Connection connection = factory.newConnection();
//创建管道
Channel channel = connection.createChannel();
//声明队列
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
//让当前线程睡眠8s,以检验rabbitmq的消息轮询
Thread.currentThread().sleep(8000);
String message = "hello,world";
//发送消息
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println("[x] send the message"+message);
channel.close();
connection.close();
}catch (Exception e) {
System.out.println("程序出错:"+e);
} }
}
消费者方(Consummer.java):
package RabbitMQTest;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
/**
* 本程序为了练习rabbitmq的简单操作
*
* @author STEVEN
*
*/
public class Consumer {
public static void main(String[] args) {
try {
//创建连接工厂对象
ConnectionFactory factory = new ConnectionFactory();
//设置工厂对象的参数,用来连接rabbitmq
factory.setHost("localhost");
//建立程序与rabbitmq的socket连接
Connection connection = factory.newConnection();
//创建管道
Channel channel = connection.createChannel();
//声明队列
channel.queueDeclare(Productor.QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
//创建队列消费对象
QueueingConsumer consumer = new QueueingConsumer(channel);
//设置参数
channel.basicConsume(Productor.QUEUE_NAME, true, consumer);
//创建接收对象来接收来自服务端的消息
Delivery delivery = null;
//循环接收,相当于开启了一个监听
while (true) {
delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
}
} catch (Exception e) {
System.out.println(e);
}
}
}