- 自己创建连接对象
导入依赖
自己创建连接对象org.springframework.boot spring-boot-starter-amqp
连接对象的工具类
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class RabbitMqUtil {
private static ConnectionFactory connectionFactory;
static {
// 重量级资源 ,让其类加载是执行一次即可
connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.10.166");
connectionFactory.setPort(5672);
// 设置虚拟主机
connectionFactory.setVirtualHost("ems");
// 设置访问虚拟主机的用户名和密码
connectionFactory.setUsername("admin");
connectionFactory.setPassword("admin");
}
// 获取连接对象的方法
public static Connection getConnection() {
try {
// 创建连接
return connectionFactory.newConnection();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 关闭通道和关闭连接的方法
public static void closeConnection(Channel channel, Connection connection) {
try {
if (channel != null) {
channel.close();
}
if (connection != null) {
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
生产消息代码
public static void main(String[] args) throws IOException, TimeoutException {
// 创建连接
Connection connection = RabbitMqUtil.getConnection();
// 获取连接通道
Channel channel = connection.createChannel();
// 通道绑定对象
channel.queueDeclare("topic",false,false,false,null);
// 消费消息 参数1 队列名称 参数2 开始消息的自动确认机制 参数3 消费时的回调接口
channel.basicConsume("topic",true,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("======" + new String(body));
}
});
}
管理界面和代码参数的对应关系
消费者代码
public static void main(String[] args) throws IOException {
// 创建连接
Connection connection = RabbitMqUtil.getConnection();
// 获取连接通道
Channel channel = connection.createChannel();
// 通道绑定对象
channel.queueDeclare("topic", false, false, false, null);
// 通道绑定对应消息队列
// 参数1 队列名称 ,参数2 用来定义队列特性是否要持久化 true 持久化 false 不持久化
// 参数3 exclusive 是否独占队列 true 独占队列 false 不独占队列
// 参数4 autoDelete 是否在消费完成后自动删除,true 自动删除 false 不自动删除
// 参数5 额外附加参数
channel.queueDeclare("topic",false,false,false,null);
// 发布消息 参数1 交换机名 参数名 队列名 参数3传递消息的额外设置 参数4 消息内容
channel.basicPublish("","topic",null,"hellomq3".getBytes());
RabbitMqUtil.closeConnection(channel, connection);
}



