RabbitMQ的三种模式-----分列模式(Fanout)

分列模式(Fanout):

当我们需要将消息一次发给多个队列时,需要使用这种模式

1:简述:

任何发送到Fanout Exchange的消息都会被转发到与该Exchange绑定(Binding)的所有 Queue上。
1.可以理解为路由表的模式
2.这种模式不需要RouteKey

3.这种模式需要提前将Exchange与Queue进行绑定,一个Exchange可以绑定多个 Queue,一个Queue可以同多个Exchange进行绑定。多对多的关系。
4.如果接受到消息的Exchange没有与任何Queue绑定,则消息会被抛弃。 

2:交换器绑定队列

(1):新增队列  test1 和 test2

(2):新增交换器  wchExchange

(3):将队列和交换器绑定

点击 wchExchange 进入交换器管理界面,操作后如下图:

3:代码实现:

代码参考:https://gitee.com/WChengHe/RabbitmqDemo

代码中pom文件、配置文件及启动类参考上一篇:https://blog.csdn.net/qq_22596931/article/details/89329024

测试类FanoutTest.java:

package com.wch.demo.fanout;

import com.wch.demo.DemoApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class FanoutTest {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void testSendFanout(){
        rabbitTemplate.convertAndSend("wchExchange","","测试分列模式");

    }
}

在编写完测试类后,我们可以运行一下这个类,然后在界面:http://192.168.225.100:15672/#/queues,可以查看到我们交换器绑定的两个队列都保存有一条消息,说明是正常的。

 

在上述内容之后我们可以开始编写消费者:

消费者Customer2.java

package com.wch.demo.fanout;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "test1")
public class Customer2 {

    @RabbitHandler
    public void showMessage(String message){
        System.out.println("test1接收到消息:"+message);

    }
}

消费者Customer3.java

package com.wch.demo.fanout;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "test2")
public class Customer3 {

    @RabbitHandler
    public void showMessage(String message){
        System.out.println("test2接收到消息:"+message);

    }
}

完成上述代码编写后进行测试,运行后查看控制台:

在控制台中我们可以看到,生成的消息被消费者消费了。

附代码:https://gitee.com/WChengHe/RabbitmqDemo

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值