查看内容 https://zhangc233.github.io/2021/07/23/RabbitMQ/
1. 创建SpringBoot项目,引入相关依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2. 编写生产者代码
/**
* 生产者
*/
public class Producer {
//消息队列名称
public static final String QUEUE_NAME = "hello";
//发消息
public static void main(String[] args) throws Exception {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//工厂ip,连接RabbitMQ的队列
factory.setHost("120.24.192.216");
//用户名
factory.setUsername("admin");
//密码
factory.setPassword("123456");
//创建连接
Connection connection = factory.newConnection();
//获取信道,使用信道发消息
Channel channel = connection.createChannel();
/**
* 声明一个队列
* 1.队列名称
* 2.队列里面的消息是否持久化
* 3.消息是否共享
* 4.是否自动删除。最后一个消费者断开连接后是否自动删除
* 5.其他参数
*/
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
//发消息
String message = "hello world";
/**
* 发送消息
* 1.发送到哪个交换机
* 2.路由的key值是哪个,本次是队列的名称
* 3.其他参数
* 4.发送消息的消息体
*/
channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
System.out.println("消息发送完毕");
}
}
3. 编写消费者代码
/**
* 消费者
*/
public class Consumer {
//消息队列名称,队列名称需和生产者一致
public static final String QUEUE_NAME = "hello";
//接收消息
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("120.24.192.216");
factory.setUsername("admin");
factory.setPassword("123456");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
System.out.println("等待接收消息.........");
//推送的消息如何进行消费的接口回调
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody());
System.out.println(message);
};
//取消消息时的回调
CancelCallback cancelCallback = (consumerTag) -> {
System.out.println("消息消费被中断");
};
/**
* 消费者消费消息 - 接受消息
* 1.消费哪个队列
* 2.消费成功之后是否要自动应答 true 代表自动应答 false 手动应答
* 3.消费者未成功消费的回调
* 4.消息被取消时的回调
*/
channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback);
}
}
4. 运行测试
打开 http://120.24.192.216:15672/ 这里的ip为增加服务器的ip地址,里面可以看到消息发送接收的相关信息
运行发送者代码,提示消息发送完毕
运行消费者代码,接收得到消息