通常使用RabbitMq需要先在RabbitMq控制台上创建vhost,exchange,queue,然后创建进行routingkey绑定。当然这个操作也可以通过对应API来操作。
当然如果使用了Spring,整个绑定过程就相对容易点了。毕竟在控制台上创建和绑定是比较麻烦的,而且换了环境之后还要重复这个流程。
方式一:
用过@Bean的方式创建绑定关系
package cn.kanyun.module;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyRabbitMqConfig {
/**
* description 配置交换机,不同类型的可以声明成不同的,比如fanout、direct、topic等
* param durable:持久性 autoDelete:自动删除
* return org.springframework.amqp.core.DirectExchange
**/
@Bean
DirectExchange myDirectExchange(){
// name:交换机的名称
// durable:交换机有持久(durable)和暂存(transient)两个状态。
// autoDelete:当所有与之绑定的消息队列都完成了对此交换机的使用后,删掉它。默认是true
return new DirectExchange("KanyunExchange",true,false);
}
/**
* description 配置队列
* param durable,autoDeletet,exclusive
* return org.springframework.amqp.core.Queue
* createTime 2020/9/14 18:54
**/
@Bean
Queue myDirectQueue(){
//durable,autoDeletet:
//exclusive:只被一个连接使用,当连接关闭后,队列即将被删除
return new Queue("myDirectQueue",true,false,false);
}
/**
* description 绑定 同时配置路由键
* 队列与交换机的绑定,通过routingKey来绑定,fanout模式是不需要routingKey的,因为他是直接绑定队列的
* param []
* return org.springframework.amqp.core.Binding
* createTime 2020/9/14 19:03
**/
@Bean
Binding myDirectBinding(){
// 队列 -> 交换机 -> 路由键
return BindingBuilder.bind(myDirectQueue()).to(myDirectExchange()).with("myDirectRoutingKey");
}
//可以绑定多个
// @Bean
// public Binding mybind1(){
// return BindingBuilder.bind(queue).to(topicExchange).with("topic.#");
// }
// @Bean
// public Binding mybind2(){
// return BindingBuilder.bind(queue1).to(topicExchange).with("topic.*");
// }
}
可以看到通过上面的配置,当项目启动后,交换机,队列以及绑定关系都创建好了。这种方式其实看起来比较麻烦,因为写了比较多的@Bean,看起来眼花缭乱。
方式二:
只配置消费者。
@RabbitListener(bindings = {@QueueBinding(value = @Queue(value="kanyun.queue",durable = "true"),
exchange = @Exchange(value = "kanyun_exchange_1",durable = "true"),key = "kanyun.route.key")})
public void handleMessage(byte[] message){
System.out.println("消费消息");
System.out.println(new String(message));
}
使用这种方式也可以自动创建交换机,队列以及绑定关系。比上一种方式更直观。但是没有第一种方式灵活。
application.yml
spring:
rabbitmq:
addresses: 127.0.0.1:5672
username: guest
password: guest
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>