springboot整合rabbitMQ
- 1、添加依赖。springboot提供了与rabbitMQ进行整合的依赖,因此需要将springboot与rabbitMQ的依赖添加到pom.xml文件中。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
- 2、编写springboot与rabbitMQ的整合配置类。
@Configuration
public class SpringRabbitMQConfig {
final static String queueName = "queue.demo"; //这里是队列的名称,交换机和队列进行绑定有个匹配模式,当producer 发送数据到指定路由键queue.demo或与 绑定的匹配模式进行匹配。
/**
* 定义一个队列
* @return
*/
@Bean
Queue queue() {
return new Queue(queueName, false);
}
/**
* 定义一个topic交换机
* @return
*/
@Bean
public TopicExchange topicExchange(){
TopicExchange exchange=new TopicExchange("spring-boot-topicExchange");
return exchange;
}
/**
* 让队列和交换机绑定
* @param queue 参数名称必须是queue,springboot默认使用的时方法名。-->对应上面的queue()方法
* @param topicExchange 参数必须是topicExchange ,springboot默认使用的是方法名-->对应上面的topicExchange()方法
* @return
*/
@Bean
public Binding bindingQueueAndTopicExchange(Queue queue,TopicExchange topicExchange){
return BindingBuilder.bind(queue).to(topicExchange).with("queue.#");//路由匹配,这里是路由匹配规则。
}
}
-3、编写生产者处理类
@Component
public class MQSendHandler {
@Autowired
private AmqpTemplate amqpTemplate;//springboot会帮我们创建。
public void send(){
String sendMsg = "hello " + new Date();
System.out.println("rabbit生产者发送消息 : " + sendMsg);
amqpTemplate.convertAndSend("spring-boot-topicExchange", "queue.demo", sendMsg);
//第一个参数:交换机的名字,我们在第二步,声明了topic交换机名称为spring-boot-topicExchange的交换机,因此这里写spring-boot-topicExhchange
第二个参数:队列的名称,我们在第二步,配置了名字为queue.demo的队列,因此这里写的是queue.demo
第三个参数:要发送的消息数据。
说明:当生成这发送数据到mq后,首先会寻找与路由键匹配的绑定模式,而我们的匹配规则是queue.# (其中#标示0个或多个,*标示至少有一个),因此这里发送的数据会被被queue.demo的队列消费。
}
}
- 4、编写消费者处理类
@Component
@RabbitListener(queues = "queue.demo")//这里写的是监听的是哪个队列。
public class MQReceiverHandler {
@RabbitHandler
public void process(String message) {
System.out.println("接受端 : " + message);
}
}
-5、springboot配置文件application.properties或者application.yml配置rabbitMQ的配置
spring.rabbitmq.host=192.168.1.215
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=123456