定义
广播消息是指生产者产生的消息将分发给所有订阅这个消息的消费者,而普通的模式是:一批消息可以被多个人共同消费,如consumer1可能消费1,3,5记录,而consumer2可能消费的是2,4,6这种模块就是共同消费模块;而今天说的是广播消息,它是指一些消息同时被推送到多个订阅者,而这些订阅者收到的消息都是完整的,如consumer1收到的会是1,2,3,4,5,6,而consumer2回到的也会是1,2,3,4,5,6,这种就像广播一样,把消息广播给多人!
实质上是对Fanout类型的exchange的实现
通过我们RabbitMq的后台可以看到,它会使用fanout模式,并且会自己添加队列,当然队列名称也是动态的.
广播模式的生产者
static void TestFanout(int _index) { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { const string EXCHANGE_NAME = "logs"; const string ROUTING_KEY = ""; channel.ExchangeDeclare(EXCHANGE_NAME, "fanout");//广播 var message = "hello out"; var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(EXCHANGE_NAME, ROUTING_KEY, null, body);//不需要指定routing key,设置了fanout,指了也没有用. Console.WriteLine(" [x] Sent {0}", message + _index); } } }
广播模式的消费者
static void TestFanout() { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { const string EXCHANGE_NAME = "logs"; const string ROUTING_KEY = ""; channel.ExchangeDeclare(EXCHANGE_NAME, "fanout");//广播 QueueDeclareOk queueOk = channel.QueueDeclare(); string queueName = queueOk.QueueName; channel.QueueBind(queueName, EXCHANGE_NAME, ROUTING_KEY);//不需要指定routing key,设置了fanout,指了也没有用. var consumer = new QueueingBasicConsumer(channel); channel.BasicConsume(queueName, true, consumer); Console.WriteLine(" [*] Waiting for messages." + "To exit press CTRL+C"); while (true) { var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();//挂起的操作 var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); } } } }
通过测试我们发布,由producer生产的消息,已经被推送到所有消费者那边了...
以上就是RabbitMQ的广播模式,通过本讲的学习,我们知道队列的又一用法!
感谢各位的阅读!
本文转自博客园张占岭(仓储大叔)的博客,原文链接:RabbitMQ~广播消息,如需转载请自行联系原博主。