java-rabbitmq-官网实例01


描述:最简单实例,使用非持久化队列,生产者发布消息,MQ 将消息推送给消费者消费,之后 MQ 在队列中删除该消息


依次运行:D1_Send.main();D1_Recv.main();

package com.example.tutorials;


import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;


import java.util.Scanner;


/**
* 最简单实例,使用非持久化队列,生产者发布消息,MQ 将消息推送给消费者消费,之后 MQ 在队列中删除该消息
* 发送消息到"默认交换器",默认交换器是一个无名直连交换器
* @create 2017-08-29
* amqp-client 4.2.0
**/
public class D1_Send {
private final static String QUEUE_NAME = "hello";


/**
* 生产者, "Hello World!"
* @param argv
* @throws Exception
*/
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
//设置登录账号
factory.setHost(ServerInfo.host);
factory.setPort(ServerInfo.port);
factory.setUsername(ServerInfo.uName);
factory.setPassword(ServerInfo.uPwd);
//链接服务器
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//定义一个队列
boolean duiable=false;//持久化
boolean exclusive = false;//排他队列
boolean autoDelete=false;//没有consumer时,队列是否自动删除
channel.queueDeclare(QUEUE_NAME, duiable, exclusive, autoDelete, null);


//发送消息
System.out.println("输入要发送的消息,退出输入 x ");
String message = "Hello World!";
do{
Scanner scanner = new Scanner(System.in);
message = scanner.next();
channel.basicPublish(""
, QUEUE_NAME
, null
, message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + message + "'");
}while(!"x".equals(message));
//关闭链接
channel.close();
connection.close();
}
}




package com.example.tutorials;


import com.rabbitmq.client.*;


import java.io.IOException;


/**
* 最简单实例,使用非持久化队列,生产者发布消息,MQ 将消息推送给消费者消费,之后 MQ 在队列中删除该消息
* 发送消息到"默认交换器",默认交换器是一个无名直连交换器
* @create 2017-08-29
* amqp-client 4.2.0
**/
public class D1_Recv {
private final static String QUEUE_NAME = "hello";


/**
* 消费者, "Hello World!"
* @param argv
* @throws Exception
*/
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
//设置登录账号
factory.setHost(ServerInfo.host);
factory.setPort(ServerInfo.port);
factory.setUsername(ServerInfo.uName);
factory.setPassword(ServerInfo.uPwd);
//链接服务器
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//定义一个队列
boolean duiable=false;//持久化
boolean exclusive = false;//排他队列
boolean autoDelete=false;//没有consumer时,队列是否自动删除
channel.queueDeclare(QUEUE_NAME, duiable, exclusive, autoDelete, null);


//接收消息
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + message + "'");
}
};
//启动消费者,接收消息
boolean autoAck=true;//自动应答,true=自动发送应答;false=手动发送应答;
channel.basicConsume(QUEUE_NAME, autoAck, consumer);
}
}