1.创建连接工具类
package com.xingli.mqTset;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* @ClassName ConnectionUtil
* @Description TODO
* @Author William
* @Date 2019/9/18 14:14
* @Version 1.0
*/
public class ConnectionUtil {
public static Connection getConnection() throws Exception {
//定义连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置服务地址
factory.setHost("localhost");
//端口
factory.setPort(5672);
//设置账号信息,用户名、密码、vhost
factory.setVirtualHost("testhost");
factory.setUsername("mqUser");
factory.setPassword("mqUser");
// 通过工程获取连接
Connection connection = factory.newConnection();
return connection;
}
public static void main(String[] args) {
try {
Connection connection = getConnection();
System.out.println("获取连接成功");
} catch (Exception e) {
System.out.println("获取连接失败");
e.printStackTrace();
}
}
}
2.简单的消息发送
package com.xingli.mqTset;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
/**
* @ClassName Send
* @Description TODO
* @Author William
* @Date 2019/9/18 14:32
* @Version 1.0
*/
public class Send {
private final static String QUEUE_NAME = "testSimple";
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!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" send'" + message + "'");
//关闭通道和连接
channel.close();
connection.close();
}
}
3.消息接收
package com.xingli.mqTset;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;
/**
* @ClassName Recv
* @Description TODO
* @Author William
* @Date 2019/9/18 14:34
* @Version 1.0
*/
public class Recv {
private final static String QUEUE_NAME = "testSimple";
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);
// 监听队列
channel.basicConsume(QUEUE_NAME, true, consumer);
// 获取消息
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" Received '" + message + "'");
}
}
}
注意:消息的发送和接收队列必须是同一个队列,名字不要错了