Springboot整合RabbitMQ
在springboot中使用RabbitMQ需要以下几个步骤:
1. 在pom文件中导入依赖
2. 生产者使用RabbitMQ发送消息
3. 消费者监听RabbitMQ中的消息
Springboot整合RabbitMQ
1. 在pom中导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2. 生产者使用RabbitMQ发送消息
在springboot中使用RabbitMQ需要以下步骤:
生产者:
1. 在配置文件中配置 RabbitMQ 的信息
2. 创建交换机和队列, 完成交换机和队列的绑定
3. 使用 RabbitTemplate 发送消息
消费者:
1. 在配置文件中配置RabbitMQ的信息
2. 配置监听器监听消息队列
3. 代码
包括生产者和消费者的代码
3.1 生产者
- 配置文件,这里是yml格式,properties同理
spring:
rabbitmq:
host: localhost # 主机地址
port: 5672 # 端口号
username: cxrlover # 登录用的用户名
password: ****** # 密码
virtual-host: /cxrloverVH # 该工程使用的virtual-host地址
- 创建交换机和队列, 完成交换机和队列的绑定
如果已经创建好了交换机、队列、交换机和队列的绑定,可以跳过该步骤继续下一个步骤
/**自己创建队列和交互机。*/
@Configuration
public class RabbitConfiguration {
// 事先定义交换机和队列的名称
public static String exchange_name01="springboot-topic-exchange";
private String queue_name01="springboot-topic-queue01";
private String queue_name02="springboot-topic-queue02";
/**
* 创建交互机,这里采用topic模式
* @return
*/
@Bean
public Exchange buildExchange(){
return ExchangeBuilder.topicExchange(exchange_name01).build();
}
/**
* 创建队列
* @return
*/
@Bean("queue01")
public Queue buildQueue01(){
return QueueBuilder.durable(queue_name01).build();
}
/**
* 创建队列
* @return
*/
@Bean("queue02")
public Queue buildQueue02(){
return QueueBuilder.durable(queue_name02).build();
}
/**
* 队列01和交互机进行绑定
*/
@Bean
public Binding binding01(Queue queue01,Exchange exchange){
return BindingBuilder.bind(queue01).to(exchange).with("*.orange.*").noargs();
}
/**
* 队列02和交互机进行绑定
*/
@Bean
public Binding binding02(Queue queue02,Exchange exchange){
return BindingBuilder.bind(queue02).to(exchange).with("*.*.rabbit").noargs();
}
/**
* 队列02和交互机进行绑定
*/
@Bean
public Binding binding03(Queue queue02,Exchange exchange){
return BindingBuilder.bind(queue02).to(exchange).with("lazy.#").noargs();
}
}
- 使用 RabbitTemplate 发送消息,这里只是做一个演示
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void contextLoads() {
Map<String,Object> message=new HashMap<>();
message.put("product_id",10);
message.put("num",50);
message.put("price",600);
/*
* String exchange 交换机名称
* String routingKey 路由key
* final Object object 要发送的消息
*/
rabbitTemplate.convertAndSend(
RabbitConfiguration.exchange_name01, // 交换机名称
"hello.orange.abc", // 路由key
JSON.toJSONString(message)); //发送的消息
}
3.2 消费者
- 配置文件信息,yml格式
spring:
rabbitmq:
host: localhost
port: 5672
username: cxrlover
password: ******
virtual-host: /cxrloverVH
- 监听器文件
@Component
public class MyListener {
@RabbitListener(queues = {"springboot-topic-queue01"}) // 值是要监听的队列名称
public void message(String msg){
//根据消息 写自己的业务代码
System.out.println(msg);
}
}
到这里就整合结束了!!