目录
1.创建项目和模块
2.添加rabbitMQ依赖
3.启动rabbitMQ服务
4.引入rabbitMQ服务端信息
5.通过单元测试模拟业务发送消息
6. 接收消息
1.创建项目和模块
2.添加rabbitMQ依赖
<!-- rabbitmq依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
3.启动rabbitMQ服务
登录
4.引入rabbitMQ服务端信息
spring:rabbitmq:port: 5672host: localhostusername: guest rabbitMQ服务端账号password: guest rabbitMQ服务端密码 virtual-host: / 虚拟机地址
rabbitMQ服务端用户和虚拟机操作可参考
https://blog.csdn.net/m0_67930426/article/details/134905566
5.通过单元测试模拟业务发送消息
package com.example.publisher;import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class SendMessage {@Autowiredprivate RabbitTemplate rabbitTemplate;@Testvoid TestSend(){String queueName="aaa.queue";String msg="我正在使用rabbitMQ";rabbitTemplate.convertAndSend(queueName,msg);}}
运行成功
如果队列未接收到msg,很可能是交换机未绑定该队列
因为生产者发送消息,经过交换机,再到队列,最终由消费者监听,接收消息
交换机绑定队列可以参考
https://blog.csdn.net/m0_67930426/article/details/134904365?spm=1001.2014.3001.5501
6. 接收消息
package com.example.consumer.mqListener;import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;@Slf4j
@Component
public class Listener {@RabbitListener(queues = "bbb.queue")public void bbb(String msg){System.out.println("消费者收到了bbb.queue的消息:【"+msg+"】");}
}
即
运行