普通模式
一个生产者,一个交换机,一个队列,一个消费者.
生产者
public class Send {
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws IOException, TimeoutException {
// 初始化
ConnectionFactory factory = new ConnectionFactory();
// 这里需要设置主机名,端口,密码等,这里使用的工厂默认的配置
Connection connection = factory.newConnection();// 获取连接
Channel channel = connection.createChannel();// 获取通道
//声明队列
/** 队列声明的参数
* @param queue the name of the queue
* @param durable true if we are declaring a durable queue (the queue will survive a server restart)
* @param exclusive true if we are declaring an exclusive queue (restricted to this connection)
* @param autoDelete true if we are declaring an autodelete queue (server will delete it when no longer in use)
* @param arguments other properties (construction arguments) for the queue
*/
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
//定义消息
String message = "hello world";
// 发送消息
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
// 断开连接
channel.close();
connection.close();
}
}
消费者:
public class Recv {
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();