笔记内容大部分于来自b站视频 黑马程序员RabbitMQ全套教程,rabbitmq消息中间件到实战
一.生产者
1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.在application.yaml文件中进行配置
spring:
rabbitmq:
addresses: 你的rabbitMQ所在服务器的ip地址和对应端口(5672)
username: 你的用户名
password: 密码
3.写一个配置类
@Configuration
public class RabbitMQConfig {
public static final String EXCHANGE_NAME = "boot_topic_exchange";
public static final String QUEUE_NAME = "boot_queue";
//1.交换机
@Bean("bootExchange")
public Exchange bootExchange(){
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
}
//2.队列
@Bean("bootQueue")
public Queue bootQueue(){
return QueueBuilder.durable(QUEUE_NAME).build();
}
//3.队列和交换机的绑定关系
@Bean
public Binding binding(@Qualifier("bootQueue") Queue queue,@Qualifier("bootExchange") Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
}
}
4.测试
@SpringBootTest
class RabbitMQApplicationTests {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void producer(){
//发送消息
String message = "hello rabbitmq";
rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.hhh",message);
}
}
二.消费者
1.前两步和生产者一样
2.添加监听RabbitMQ中队列消息的组件
@Component
public class RabbitMQListener {
@RabbitListener(queues = "boot_queue")//这里的boot_queue是一个队列名,和生产者的String QUEUE_NAME = "boot_queue"相对应。
public void ListenerQueue(Message message){
String s = new String(message.getBody());
System.out.println(s);
}
}