基本概念
channel:消息通道
exchage:消息路由规则,四种模式(topic、direct、fanout、header)
direct:默认,根据routingKey完全匹配,好处是先匹配再发送
topic:根据绑定关键字通配符规则匹配、比较灵活
fanout:不需要指定routingkey,相当于群发
header:不太常用,可以自定义匹配规则
queue:消息存储
routerKey:消息路由关键字(发送的时候成为bindingkey,接收成为routingKey)
队列的概念(
生产者消费者启动报错大多数都是这几个不匹配导致)
durable:持久化到硬盘
exclusive:唯一性
autoDelete:自动删除
springboot如何集成
@Configuration
public class RabbitConfig {
// 发送消息的格式转换器
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate template = new RabbitTemplate(connectionFactory);
template.setMessageConverter(new Jackson2JsonMessageConverter());
return template;
}
// 接收消息的格式转换器
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setMessageConverter(new Jackson2JsonMessageConverter());
return factory;
}
// 信道配置,此地使用direct模式
@Bean
public DirectExchange defaultExchange() {
return new DirectExchange(MQConstant.EXCHANGE, true, false);
}
// 配置队列规则属性 例如保活时间 持久化 是否自动删除等
@Bean
public Queue queue() {
Map<String, Object> arguments = new HashMap<>();
arguments.put("x-message-ttl", 25000);//25秒自动删除
Queue queue = new Queue(MQConstant.QUEUE_NAME, true, false, true, arguments);
return queue;
}
// 绑定队列和exchange
@Bean
public Binding binding() {
return BindingBuilder.bind(queue()).to(defaultExchange()).with(MQConstant.QUEUE_NAME);
}
}
如何发送
@Autowired
private RabbitTemplate template;
//convertAndSend和send的区别是这个convert更方便使用,可以传object进去
template.convertAndSend(MQConstant.EXCHANGE, bindingKey, msg);
//如何接收,注意队列名称、exchange名称、routingKey的指定。
//注意:队列的消息只要被一个消费者匹配消费后就不存在了
@Component
@RabbitListener(containerFactory = "rabbitListenerContainerFactory", bindings = @QueueBinding(value = @Queue(value = "default_queue", durable = "true"), exchange = @Exchange(value = "default_exchange", type = ExchangeTypes.TOPIC), key = "meeting"))
@Log4j
public class RabbitMqListener {
@RabbitHandler
public void processMessage(MqMsg message) {
log.error( message);
}
}