SpringAMQP发布、订阅——Fanout Exchange交换机代码模拟

发布订阅模型:

MQ提供了很多交换机模型 其中常用的有下边三个:

Fanout:广播

Direct:路由

Topic:话题

转换器只负责消息路由,不是存储,路由失败则消息丢失

Fanout Exchange:会将接收到的消息路由导每一个跟其绑定的queue.

利用SpringAMQP演示FanoutExchange的使用:

实现代码:

在consumer编写工具类,实现交换机和队列的绑定:

package cn.itcast.mq.configu;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @className:cn.itcast.mq.configu.BindExchangeToQueue
 * @description:by-li
 * @author:Administrator
 * @create:2024-05-1116:33
 */
@Configuration
public class BindExchangeToQueue {

    //声明交换机
    @Bean
    public FanoutExchange fanoutExchange() {
        return new FanoutExchange("itcast.fanout");
    }

    //生命queue
    @Bean
    public Queue fanoutqueue1() {
        return new Queue("itcast.queue1");
    }

    @Bean
    public Queue fanoutqueue2() {
        return new Queue("itcast.queue2");
    }

    //绑定交换机
    @Bean
    public Binding fanoutExchangeToQueue1Bind(Queue fanoutqueue1, FanoutExchange fanoutExchange){
        return BindingBuilder.bind(fanoutqueue1).to(fanoutExchange);//绑定交换机和队列
    }

    @Bean
    public Binding fanoutExchangeToQueue2Bind(Queue fanoutqueue2, FanoutExchange fanoutExchange){
        return BindingBuilder.bind(fanoutqueue2).to(fanoutExchange);//绑定交换机和队列
    }

}

在consumer实体类里编写接收两个队列请求的方法:

    @RabbitListener(queues = "itcast.queue1")
    public void lintestFanoutExchangeToQueue1(String mes) throws InterruptedException {
        System.out.println("从队列1中获取到了消息:"+mes);
        Thread.sleep(200);
    }

    @RabbitListener(queues = "itcast.queue2")
    public void lintestFanoutExchangeToQueue2(String mes) throws InterruptedException {
        System.out.println("从队列2中获取到了消息:"+mes);
        Thread.sleep(200);
    }

在publisher里编写测试方法 模拟给交换机发送消息:

//给FanoutExchange交换机发送消息
    @Test
    public void testFanoutExchangeSend(){
        String FanoutChangeName = "itcast.fanout";
        String msg="我是fannout发送的消息";
        rabbitTemplate.convertAndSend(FanoutChangeName,"",msg);
    }

然后发送请求和启动consumer类,在控制台查看:

这里看到我们只发送了一条消息,但是两个consumer消费者都接收到了消息,能看出来Fanout Exchange交换机将收到的消息发到了给他绑定的两个queue里了

总结:

  • 18
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值