设为首页 收藏本站
查看: 1032|回复: 0

[经验分享] 【RabbitMQ Tutorials】3 Publish/Subscribe

[复制链接]

尚未签到

发表于 2017-12-8 23:32:29 | 显示全部楼层 |阅读模式
  In the previous tutorial we created a work queue. The assumption behind a work queue is that each task is delivered to exactly one worker. In this part we'll do something completely different -- we'll deliver a message to multiple consumers. This pattern is known as "publish/subscribe".
  To illustrate the pattern, we're going to build a simple logging system. It will consist of two programs -- the first will emit(vt. 发出,放射;发行;发表) log messages and the second will receive and print them.
  In our logging system every running copy of the receiver program will get the messages. That way we'll be able to run one receiver and direct the logs to disk; and at the same time we'll be able to run another receiver and see the logs on the screen.
  Essentially(adv. 本质上;本来), published log messages are going to be broadcast(vt. 播送,播放;(无线电或电视)广播;) to all the receivers.

Exchanges
  In previous parts of the tutorial we sent and received messages to and from a queue. Now it's time to introduce the full messaging model in Rabbit.
  Let's quickly go over what we covered in the previous tutorials:


  • A producer is a user application that sends messages.
  • A queue is a buffer that stores messages.
  • A consumer is a user application that receives messages.
  The core idea in the messaging model in RabbitMQ is that the producer never sends any messages directly to a queue. Actually, quite often the producer doesn't even know if a message will be delivered to any queue at all.
  Instead, the producer can only send messages to an exchange. An exchange is a very simple thing. On one side it receives messages from producers and the other side it pushes them to queues. The exchange must know exactly what to do with a message it receives. Should it be appended to a particular queue? Should it be appended to many queues? Or should it get discarded. The rules for that are defined by the exchange type.
DSC0000.png

  There are a few exchange types available: direct, topic, headers and fanout(n. 扇出;展开;分列(账户)). We'll focus on the last one -- the fanout. Let's create an exchange of this type, and call it logs:



channel.ExchangeDeclare("logs", "fanout");
  The fanout exchange is very simple. As you can probably guess from the name, it just broadcasts all the messages it receives to all the queues it knows. And that's exactly what we need for our logger.

Listing exchanges
  To list the exchanges on the server you can run the ever useful rabbitmqctl:



sudo rabbitmqctl list_exchanges
  In this list there will be some amq.* exchanges and the default (unnamed) exchange. These are created by default, but it is unlikely you'll need to use them at the moment.

The default exchange
  In previous parts of the tutorial we knew nothing about exchanges, but still were able to send messages to queues. That was possible because we were using a default exchange, which we identify by the empty string ("").
  Recall how we published a message before:



var message = GetMessage(args);
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "hello",
basicProperties: null,
body: body);
  The first parameter is the the name of the exchange. The empty string denotes the default or nameless exchange: messages are routed to the queue with the name specified by routingKey, if it exists.

  Now, we can publish to our named exchange instead:



var message = GetMessage(args);
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "logs",
routingKey: "",
basicProperties: null,
body: body);
Temporary queues
  As you may remember previously we were using queues which had a specified name (remember hello and task_queue?). Being able to name a queue was crucial(adj. 重要的;决定性的;定局的;决断的) for us -- we needed to point the workers to the same queue. Giving a queue a name is important when you want to share the queue between producers and consumers.
  But that's not the case for our logger. We want to hear about all log messages, not just a subset(n. [数] 子集;子设备;) of them. We're also interested only in currently flowing messages not in the old ones. To solve that we need two things.
  Firstly, whenever we connect to Rabbit we need a fresh, empty queue. To do this we could create a queue with a random name, or, even better - let the server choose a random queue name for us.
  Secondly, once we disconnect the consumer the queue should be automatically deleted.
  In the .NET client, when we supply no parameters to queueDeclare() we create a non-durable(adj. 耐用的,持久的), exclusive(adj. 独有的;排外的;专一的), autodelete queue with a generated name:



var queueName = channel.QueueDeclare().QueueName;
  At that point queueName contains a random queue name. For example it may look like amq.gen-JzTY20BRgKO-HjmUJj0wLg.

Bindings
DSC0001.png

  We've already created a fanout exchange and a queue. Now we need to tell the exchange to send messages to our queue. That relationship between exchange and a queue is called a binding.



channel.QueueBind(queue: queueName,
exchange: "logs",
routingKey: "");
  From now on the logs exchange will append messages to our queue.

Listing bindings
  You can list existing bindings using, you guessed it,



rabbitmqctl list_bindings
Putting it all together
DSC0002.png

  The producer program, which emits log messages, doesn't look much different from the previous tutorial. The most important change is that we now want to publish messages to our logsexchange instead of the nameless one. We need to supply a routingKey when sending, but its value is ignored for fanout exchanges. Here goes the code for EmitLog.cs file:



using System;
using RabbitMQ.Client;
using System.Text;
class EmitLog
{
public static void Main(string[] args)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using(var connection = factory.CreateConnection())
using(var channel = connection.CreateModel())
{
channel.ExchangeDeclare(exchange: "logs", type: "fanout");
var message = GetMessage(args);
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "logs",
routingKey: "",
basicProperties: null,
body: body);
Console.WriteLine(" [x] Sent {0}", message);
}
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
private static string GetMessage(string[] args)
{
return ((args.Length > 0)
? string.Join(" ", args)
: "info: Hello World!");
}
}
  (EmitLog.cs source)
  As you see, after establishing the connection we declared the exchange. This step is necessary as publishing to a non-existing exchange is forbidden.
  The messages will be lost if no queue is bound to the exchange yet, but that's okay for us; if no consumer is listening yet we can safely discard the message.
  The code for ReceiveLogs.cs:



using System;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
class ReceiveLogs
{
public static void Main()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using(var connection = factory.CreateConnection())
using(var channel = connection.CreateModel())
{
channel.ExchangeDeclare(exchange: "logs", type: "fanout");
var queueName = channel.QueueDeclare().QueueName;
channel.QueueBind(queue: queueName,
exchange: "logs",
routingKey: "");
Console.WriteLine("
  • Waiting for logs.");
    var consumer = new EventingBasicConsumer(channel);
    consumer.Received += (model, ea) =>
    {
    var body = ea.Body;
    var message = Encoding.UTF8.GetString(body);
    Console.WriteLine(" [x] {0}", message);
    };
    channel.BasicConsume(queue: queueName,
    autoAck: true,
    consumer: consumer);
    Console.WriteLine(" Press [enter] to exit.");
    Console.ReadLine();
    }
    }
    }
      (ReceiveLogs.cs source)
      Follow the setup instructions from tutorial one to generate the EmitLogs and ReceiveLogs projects.
      If you want to save logs to a file, just open a console and type:



    cd ReceiveLogs
    dotnet run > logs_from_rabbit.log
      If you wish to see the logs on your screen, spawn(vt. 产卵;酿成,造成;大量生产) a new terminal and run:



    cd ReceiveLogs
    dotnet run
      And of course, to emit logs type:



    cd EmitLog
    dotnet run
      Using rabbitmqctl list_bindings you can verify that the code actually creates bindings and queues as we want. With two ReceiveLogs.cs programs running you should see something like:



    sudo rabbitmqctl list_bindings
    # => Listing bindings ...
    # => logs    exchange        amq.gen-JzTY20BRgKO-HjmUJj0wLg  queue           []
    # => logs    exchange        amq.gen-vso0PVvyiRIL2WoV3i48Yg  queue           []
    # => ...done.

      The interpretation(n. 解释;翻译;演出) of the result is straightforward(adj. 简单的;坦率的;明确的;径直的): data from exchange logs goes to two queues with server-assigned names. And that's exactly what we intended(adj. 故意的,有意的;打算中的).
      To find out how to listen for a subset of messages, let's move on to tutorial 4

  • 运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
    2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
    3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
    4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
    5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
    6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
    7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
    8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

    所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-422291-1-1.html 上篇帖子: RabbitMQ入门_15_访问控制 下篇帖子: python网络编程--RabbitMQ
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    扫码加入运维网微信交流群X

    扫码加入运维网微信交流群

    扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

    扫描微信二维码查看详情

    客服E-mail:kefu@iyunv.com 客服QQ:1061981298


    QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


    提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


    本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



    合作伙伴: 青云cloud

    快速回复 返回顶部 返回列表