概念
publisher 发布者
consumer 消费者
queue 队列
@Bean
public Queue basicQueue() {
return new Queue("basicQueue");
}
其中,basicQueue即为队列的名称
exchange 交换机
交换机有三种类型(fanout广播、direct路由、topic主题)
channel 通道
connection 连接
基本消息队列
淡蓝色代表发布者(publisher)、深蓝色代表消费者(consumer)、红色代表队列(queue)
- 基本消费队列中,有且仅有一个消费者,当提供者发布消息后,消费者会收到消息
代码实现
- 发布者
@Autowired
private RabbitTemplate rabbitTemplate;
public void basicQueuePublisher {
String queueName = "basicQueue";
String message = "hello rabbitMQ";
rabbitTemplate.convertAndSend(queueName,message);
}
- 消费者
@RabbitListener(queues = "basicQueue")
public void listenBasicQueueConsumer(String message) {
System.out.println("consumer接受到消息:" + message);
}
工作消息队列
- 一个队列有多个消费者
- 多个消费者会共同处理队列中的消息(例如:队列中有50条消息,C1、C2各自25条,而不是各自50条)
- 多个消费者会预先把消息取出来,若其中有一个消费者性能偏低,则会影响整体的性能,可以通过修改spring.listener.simple.prefetch的值来改变预取消息的数量