【RabbitMQ】使用SpringAMQP的Publish/Subscribe(发布/订阅)

Publish/Subscribe

**发布(Publish)、订阅(Subscribe):**允许将同一个消息发送给多个消费者

**注意:**exchange负责消息路由,而不是存储,路由失败则消息丢失

常见的**X(exchange--交换机)***类型:

  • Fanout 广播
  • Direct 路由
  • Topoc 话题

发布订阅--FanoutExchange

案例三:利用SpringAMQP演示广播交换机的使用

1.在消费者(consumer包)中,创建一个FanoutConfig类,声明队列、交换机,并将两者绑定
java 复制代码
@Configuration
public class FanoutConfig {
   //声明FanoutExchange交换机itcast.fanout
    @Bean
    public FanoutExchange fanoutExchange(){
        return new FanoutExchange("itcast.fanout");
    }
    //声明fanout.queue1队列
    @Bean
    public Queue fanoutQueue1(){
        return new Queue("fanout.queue1");
    }
    //绑定fanout.queue1队列和交换机
    @Bean
    public Binding bindingQueue1(Queue fanoutQueue1, FanoutExchange fanoutExchange){
        return BindingBuilder.bind(fanoutQueue1).to(fanoutExchange);
    }
    //声明fanout.queue2队列
    @Bean
    public Queue fanoutQueue2(){
        return new Queue("fanout.queue2");
    }
    //绑定fanout.queue2队列和交换机
    @Bean
    public Binding bindingQueue2(Queue fanoutQueue2, FanoutExchange fanoutExchange){
        return BindingBuilder.bind(fanoutQueue2).to(fanoutExchange);
    }
}
2.在消费者(consumer包)中,编写两个消费者SpringRabbitListener方法,分别监听fanout.queue1和fanout.queue2
java 复制代码
@Component
public class SpringRabbitListener {

    @RabbitListener(queues = "fanout.queue1")
    public void listenFanoutQueue1(String msg) {
        System.out.println("消费者接收到fanout.queue1的消息:【" + msg + "】");
    }
    @RabbitListener(queues = "fanout.queue2")
    public void listenFanoutQueue2(String msg) {
        System.out.println("消费者接收到fanout.queue2的消息:【" + msg + "】");
    }

}
3.在publiSher中编写测试方法,向itcast.fanout发送消息
java 复制代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAmqpTest {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    @Test
    public void testSendFanoutExchange() {
        // 交换机名称
        String exchangeName = "itcast.fanout";
        // 消息
        String message = "hello, every one!";
        // 发送消息
        rabbitTemplate.convertAndSend(exchangeName, "", message);
    }
}
4.运行,结果

发布订阅--DirectExchange

将接收到的消息根据规则路由到指定的Queue,因此称为路由模式(routes)

  • 每一个Queue都与Exchange设置一个BindingKey(暗号)
  • 发布者发送消息时,指定消息的RoutingKey
  • Exchange将消息路由到BindingKey与消息RoutingKey一致的队列

案例四:利用SpringAMQP演示DirectExchange的使用

1.直接用注解
@RabbitListener声明Exchange、Queue、RoutingKey
@QueueBinding注解用于绑定队列和交换器,并指定路由键
java 复制代码
@Component
public class SpringRabbitListener {
	@RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.queue1"),
            exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT),
            key = {"red", "blue"}
    ))
    public void listenDirectQueue1(String msg){
        System.out.println("消费者接收到direct.queue1的消息:【" + msg + "】");
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.queue2"),
            exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT),
            key = {"red", "yellow"}
    ))
    public void listenDirectQueue2(String msg){
        System.out.println("消费者接收到direct.queue2的消息:【" + msg + "】");
    }


}
2.测试
java 复制代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAmqpTest {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
   @Test
    public void testSendDirectExchange() {
        // 交换机名称
        String exchangeName = "itcast.direct";
        // 消息
        String message = "hello, red!";
        // 发送消息
        rabbitTemplate.convertAndSend(exchangeName, "red", message);
    }
}
3.结果

发布订阅--TopicExchange

TopicExchange与DirectExchange类似,区别在于routingKey必须是多个单词的列表,并且以**.**分割

Queue与Exchange指定BindingKey时可以使用通配符

  • # : 代指0个或多个单词
  • * : 代指一个单词

案例五:利用SpringAMQP演示TopicExchange的使用

1.直接用注解
@RabbitListener声明Exchange、Queue、RoutingKey
@QueueBinding注解用于绑定队列和交换器,并指定路由键
java 复制代码
@Component
public class SpringRabbitListener {
	 @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "topic.queue1"),
            exchange = @Exchange(name = "itcast.topic", type = ExchangeTypes.TOPIC),
            key = "china.#"
    ))
    public void listenTopicQueue1(String msg){
        System.out.println("消费者接收到topic.queue1的消息:【" + msg + "】");
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "topic.queue2"),
            exchange = @Exchange(name = "itcast.topic", type = ExchangeTypes.TOPIC),
            key = "#.news"
    ))
    public void listenTopicQueue2(String msg){
        System.out.println("消费者接收到topic.queue2的消息:【" + msg + "】");
    }
}
2.测试
java 复制代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAmqpTest {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    @Test
    public void testSendTopicExchange() {
        // 交换机名称
        String exchangeName = "itcast.topic";
        // 消息
        String message = "合理小姐是凑巧先生独一无二的女主角";
        //String message = "今天天气不错,我的心情好极了!";
        // 发送消息
         rabbitTemplate.convertAndSend(exchangeName, "china.news", message);
        //rabbitTemplate.convertAndSend(exchangeName, "china.weather", message);
    }

}
3.结果
相关推荐
阿尔的代码屋1 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者19 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者19 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh20 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅20 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽21 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django