SpringBoot整合RabbitMQ-消息生产者
主要流程是:
1.创建Springboot工程
2.依赖引入
3.编写yml配置
4.编写配置类,并定义交换机,队列等信息
5.注入RabbitTemplate,完成消息的发送
1.略
2.依赖引入
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
3.yml配置
# 配置RabbitMQ的基本信息
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
virtual-host: /
4.编写配置类
RabbitMQ有几种模式,包括简单模式,工作模式和订阅模式,具体查看官网
https://rabbitmq.com/getstarted.html
这里采用的订阅模式中的Topic,配置类信息如下:
package cn.sysu.config;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQComfig {
public static final String EXCHANGE_NAME = "ming-topic-exchange";
public static final String QUEUE_NAME1 = "ming-queue1";
public static final String QUEUE_NAME2 = "ming-queue2";
//1.创建交换机
@Bean("topic-exchange")
public Exchange createExchange(){
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
}
//2.创建交队列
@Bean("queue1")
public Queue createQueue1(){
return QueueBuilder.durable(QUEUE_NAME1).build();
}
@Bean("queue2")
public Queue createQueue2(){
return QueueBuilder.durable(QUEUE_NAME2).build();
}
//3.队列与交换机的关系 Binding
@Bean
public Binding bindQueueAndExchange1(@Qualifier("queue1") Queue queue,@Qualifier("topic-exchange") Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("test1.#").noargs();
}
@Bean
public Binding bindQueueAndExchange2(@Qualifier("queue2") Queue queue,@Qualifier("topic-exchange") Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("test2.#").noargs();
}
}
5.注入RabbitTemplate
测试类编写如下:
package cn.sysu;
import cn.sysu.config.RabbitMQComfig;
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 ProducerApplicationTest {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void contextLoads() {
rabbitTemplate.convertAndSend(RabbitMQComfig.EXCHANGE_NAME,"test1.hello","test-message1");
rabbitTemplate.convertAndSend(RabbitMQComfig.EXCHANGE_NAME,"test2.word","test-message2");
}
}
测试,显示消息发送成功
博主的坚持 离不开大家评论和点赞,感谢大家支持!!!