CopySend message : this is topc msg[x] Received 'this is topc msg'[x] Received 'this is topc msg'Fanout 模式#不处理路由键,只需要简单的将队列绑定到交换机上发送到交换机的消息都会被转发到与该交换机绑定的所有队列上 。Fanout交换机转发消息是最快的 。

文章插图
Copyimport com.rabbitmq.client.*;import java.io.IOException;public class FanoutConsumer {public static void main(String[] args) throws Exception {//1. 创建一个 ConnectionFactory 并进行设置ConnectionFactory factory = new ConnectionFactory();factory.setHost("localhost");factory.setVirtualHost("/");factory.setUsername("guest");factory.setPassword("guest");factory.setAutomaticRecoveryEnabled(true);factory.setNetworkRecoveryInterval(3000);//2. 通过连接工厂来创建连接Connection connection = factory.newConnection();//3. 通过 Connection 来创建 ChannelChannel channel = connection.createChannel();//4. 声明String exchangeName = "test_fanout_exchange";String queueName = "test_fanout_queue";String routingKey = "item.#";channel.exchangeDeclare(exchangeName, "fanout", true, false, null);channel.queueDeclare(queueName, false, false, false, null);//一般不用代码绑定,在管理界面手动绑定channel.queueBind(queueName, exchangeName, routingKey);//5. 创建消费者并接收消息Consumer consumer = new DefaultConsumer(channel) {@Overridepublic void handleDelivery(String consumerTag, Envelope envelope,AMQP.BasicProperties properties, byte[] body)throws IOException {String message = new String(body, "UTF-8");System.out.println(" [x] Received '" + message + "'");}};//6. 设置 Channel 消费者绑定队列channel.basicConsume(queueName, true, consumer);}}Copyimport com.rabbitmq.client.Channel;import com.rabbitmq.client.Connection;import com.rabbitmq.client.ConnectionFactory;public class FanoutProducer {public static void main(String[] args) throws Exception {//1. 创建一个 ConnectionFactory 并进行设置ConnectionFactory factory = new ConnectionFactory();factory.setHost("localhost");factory.setVirtualHost("/");factory.setUsername("guest");factory.setPassword("guest");//2. 通过连接工厂来创建连接Connection connection = factory.newConnection();//3. 通过 Connection 来创建 ChannelChannel channel = connection.createChannel();//4. 声明String exchangeName = "test_fanout_exchange";String routingKey1 = "item.update";String routingKey2 = "";String routingKey3 = "ookjkjjkhjhk";//任意routingkey//5. 发送String msg = "this is fanout msg";channel.basicPublish(exchangeName, routingKey1, null, msg.getBytes());channel.basicPublish(exchangeName, routingKey2, null, msg.getBytes());channel.basicPublish(exchangeName, routingKey3, null, msg.getBytes());System.out.println("Send message : " + msg);//6. 关闭连接channel.close();connection.close();}}CopySend message : this is fanout msg[x] Received 'this is fanout msg'[x] Received 'this is fanout msg'[x] Received 'this is fanout msg'作者: 海向
出处:
https://www.cnblogs.com/haixiang/p/10864339.html
本站使用「CC BY 4.0」创作共享协议,转载请在文章明显位置注明作者及出处 。
推荐阅读
- 移动WebApp高性能解决方案——MIP
- 低成本可复用前端框架——Linke
- 满足大户型用网需求——这几款路由器值得一看
- JavaScript代码整洁之道——好代码和坏代码
- python基础——数据结构栈的详解
- 最常见的鸟蛋图片 世界上最小的鸟蛋图片
- 如何下载百度文库资料——for free
- 古代最常用的兵器 中国古代有名的兵器
- 技术分享——gcc、clang、msvc等编译器的区别
- 2022新春对联大全七字创意?七字春联大全 对联2022
