package com.xzp.rabbitmq.simple;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.xzp.rabbitmq.util.ConnectionUtil;
/**
* "Hello World!"
* 简单消息
* 消息发送者 - R - 发送消息(生产者)
*
*/
public class Send {
private final static String QUEUE_NAME = "simple_queue";
public static void main(String[] argv) throws Exception {
//获取到连接以及mq通道
Connection connection = ConnectionUtil.getConnection();
//从连接中创建通道
Channel channel = connection.createChannel();
//声明(创建)队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
//定义消息内容
String message = "Hello World! My Name is suenpeng ! My Name is 2222 !";
//采用队列订阅消息
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println();
System.out.println("发送消息开始---");
System.out.println(" [x] Send '" + message + "'");
System.out.println("发送消息结束---");
System.out.println();
//关闭通道和连接
channel.close();
connection.close();
}
}
package com.xzp.rabbitmq.simple;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;
import com.xzp.rabbitmq.util.ConnectionUtil;
/**
* "Hello World!"
* 简单消息
* 消息接收者 - R - 接收消息(消费者)
*
*/
public class Recv {
private final static String QUEUE_NAME = "simple_queue";
public static void main(String[] argv) throws Exception {
// 获取到连接以及mq通道
Connection connection = ConnectionUtil.getConnection();
//声明创建通道
Channel channel = connection.createChannel();
// 声明队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
// 定义队列的消费者
QueueingConsumer consumer = new QueueingConsumer(channel);
// 监听队列
// 这里true表示"自动模式", 无需反馈,即拿走就认为消费成功。
channel.basicConsume(QUEUE_NAME, true, consumer);
// 获取消息
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println();
System.out.println("接收消息开始---");
System.out.println(" [x] Received '" + message + "'");
System.out.println("接收消息结束---");
System.out.println();
}
}
}
package com.xzp.rabbitmq.util; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; /** * Rabbit获取链接工具类 */ public class ConnectionUtil { public static Connection getConnection() throws Exception { //定义连接工厂 ConnectionFactory factory = new ConnectionFactory(); //设置服务地址 factory.setHost("localhost"); //端口 factory.setPort(5672); //设置账号信息,用户名、密码、vhost factory.setVirtualHost("/baseup"); factory.setUsername("baseup"); factory.setPassword("wukong@123"); // 通过工程获取连接 Connection connection = factory.newConnection(); return connection; } }