首先安装rabbitmq,进入rabbitmq管理页面,给出参考博客 http://blog.csdn.net/u011642663/article/details/54691788
public class Producer {
public static final String QUEUENAME="rabbit";
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory fac = new ConnectionFactory();
fac.setHost("localhost");
com.rabbitmq.client.Connection conn = fac.newConnection();
Channel ch = conn.createChannel();
// ch.queueDeclare(QUEUENAME, false, false, false, null);
String message ="helloWorld";
ch.basicPublish("", QUEUENAME, null, message.getBytes("UTF-8"));
System.out.println(message);
ch.close();
conn.close();
}
public class Consumer {
public static final String QUEUENAME="rabbit";
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory fac =new ConnectionFactory();
fac.setHost("localhost");
Connection conn = fac.newConnection();
Channel createChannel = conn.createChannel();
//createChannel.queueDeclare(QUEUENAME, false, false, true, null);rabbitmq 不允许修改以存在的队列的 参数 如果修改就会报错
//channel.queueDeclare(QUEUE_NAME, false, false, true, null);
System.out.println("Customer Waiting Received messages");
DefaultConsumer defaultConsumer = new DefaultConsumer(createChannel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8");
System.out.println("Customer Received '" + message + "'");
}
};
createChannel.basicConsume(QUEUENAME, true,defaultConsumer);
}