- 1. 创建SpringBoot项目,引入相关依赖
- 2. 编写生产者代码
- 3. 编写消费者代码
- 4. 运行测试
1. 创建SpringBoot项目,引入相关依赖查看内容 https://zhangc233.github.io/2021/07/23/RabbitMQ/
2. 编写生产者代码org.springframework.boot spring-boot-starter-amqp commons-io commons-io 2.6 org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine org.springframework.amqp spring-rabbit-test test
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();
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
//发消息
String message = "hello world";
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("消息消费被中断");
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback);
}
}
4. 运行测试
打开 http://120.24.192.216:15672/ 这里的ip为增加服务器的ip地址,里面可以看到消息发送接收的相关信息
运行发送者代码,提示消息发送完毕
运行消费者代码,接收得到消息



