SpringBoot和Spring整合RabbitMQ
具体可以网上冲浪查询
Spring
- 使用 Spring 整合 RabbitMQ 将组件全部使用配置方式实现,简化编码
- Spring 提供 RabbitTemplate 简化发送消息 API
- 使用监听机制简化消费者编码
pom.xml的依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>
SpringBoot
- SpringBoot提供了快速整合RabbitMQ的方式
- 基本信息再yml中配置,队列交互机以及绑定关系在配置类中使用Bean的方式配置
- 生产端直接注入
RabbitTemplate
完成消息发送 - 消费端直接使用
@RabbitListener
完成消息接收
pom.xml的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
yaml
spring:
rabbitmq:
host: 192.168.230.150 #主机ip
port: 5672 #端口
username: ralph
password: ralph
virtual-host: /ralphCode
生产者config
package org.ralph.rabbitmqproducerspringboot.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;
/**
* @author ralph
* @create 2022-04-06 22:56
*/
@Configuration
public class RabbitMqConfig {
public static final String EXCHANGE_NAME = "springboot_topic_exchange";
public static final String QUEUE_NAME = "springboot_queue";
/**
* declare exchanges
*/
@Bean("bootExchange")
public Exchange bootExchange(){
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
}
/**
* declare queue
*/
@Bean("bootQueue")
public Queue bootQueue(){
return QueueBuilder.durable(QUEUE_NAME).build();
}
/**
* binding queue and exchange
* @param queue queue
* @param exchange exchange
*/
@Bean
public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("springboot.#").noargs();
}
}
消费者端 Listen
package org.ralph.rabbitmq.Listner;
import org.ralph.rabbitmq.config.RabbitMqConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* @author ralph
* @create 2022-04-06 23:16
*/
@Component
public class RabbitMqListener {
/**
* define method about listener message
* queues = <listener queue name>
* @param message message
*/
@RabbitListener(queues = RabbitMqConfig.QUEUE_NAME)
public void listenerQueue(Message message){
System.out.println("message:"+ message);
}
}
rabbitmq 操控台
评论区