RABBITMQ Use (iii)

Source: Internet
Author: User
Tags emit amq

Publish/subscribe

In the previous tutorial we created a work queue. The assumption behind a work queue is, each task was 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 would consist of programs-the first would emit log messages and the second would receive and print them.

In our logging system every running copy of the receiver program would get the messages. That's the 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 in the screen.

Essentially, published log messages is going to being broadcast 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, the producer never sends any messages directly to a queue. Actually, quite often the producer doesn ' t even know if a message would be delivered to any queue at all.

Instead, the producer can only be 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 does with a message it receives. Should it is appended to a particular queue? Should it is appended to many queues? Or should it get discarded. The rules for is defined by the exchange type.

There is a few exchange types available: Direct, topic, Headers and fanout. We ' ll focus on the last one--the fanout. Let's create an exchange of this type, and call it logs:

Channel.  Exchange_declare(exchange=' logs 'type=' fanout ')     

The Fanout exchange is very simple. As 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.

Now, we can publish to our named Exchange instead:

1 channel.basic_publish (exchange='logs',2                       Routing_key =",3                       body=message)

Temporary queues

As may remember previously we were using queues which had a specified name (remember hello and task_queue?) . Being able to name a queue is crucial for us – we needed to point the workers to the same queue. Giving A queue a name is important if you want to share the queue between producers and consumers.

But that's not the case for our logger. We want to hear on all logs messages, not just a subset of them. We ' re also interested only in currently flowing messages isn't in the old ones. To solve that we need the things.

Firstly, whenever we connect to Rabbit we need a fresh, empty queue. To does it we could create a queue with a random name, or, even better-let the server choose a random queue name for us. We can do this by not supplying the queue parameter to queue_declare:

1 result = Channel.queue_declare ()

At the this point result.method.queue contains a random queue name. For example it could look like amq.gen-jzty20brgko-hjmujj0wlg.

Secondly, once we disconnect the consumer the queue should be deleted. There ' s an exclusive flag for:

1 result = Channel.queue_declare (exclusive=true)

Bindings

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 abinding.

1 channel.queue_bind (exchange='logs',2                    queue= Result.method.queue)

From now on the logs exchange would append messages to our queue.

Putting it all together

The producer program, which emits logs messages, doesn ' t look much different from the previous tutorial. The most important change is, we now want to publish messages to our logs exchange instead of the Nameless one. We need to supply a routing_key when sending, but it value is ignored for fanout exchanges. Here goes the code for emit_log.py script:

1 #!/usr/bin/env python2 ImportPika3 ImportSYS4 5Connection =Pika. Blockingconnection (Pika. Connectionparameters (6host='localhost'))7Channel =Connection.channel ()8 9Channel.exchange_declare (exchange='logs',TenType='fanout') One  AMessage =' '. Join (sys.argv[1:])or "Info:hello world!" -Channel.basic_publish (exchange='logs', -routing_key="', thebody=message) - Print "[x] Sent%r"%(message,) -Connection.close ()

(emit_log.py Source)

As you see, after establishing the connection we declared the exchange. This step is neccesary as publishing to a non-existing exchange is forbidden.

The messages would be lost if no queue was 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 receive_logs.py:

1 #!/usr/bin/env python2 ImportPika3 4Connection =Pika. Blockingconnection (Pika. Connectionparameters (5host='localhost'))6Channel =Connection.channel ()7 8Channel.exchange_declare (exchange='logs',9Type='fanout')Ten  Oneresult = Channel.queue_declare (exclusive=True) AQueue_name =Result.method.queue -  -Channel.queue_bind (exchange='logs', theQueue=queue_name) -  - Print '[*] waiting for logs. To exit Press CTRL + C' -  + defCallback (ch, method, properties, body): -     Print "[x]%r"%(body,) +  A Channel.basic_consume (Callback, atQueue=Queue_name, -no_ack=True) -  -Channel.start_consuming ()

(receive_logs.py Source)

We ' re done. If you want to save logs to a file, just open a console and type:

$ python receive_logs.py > Logs_from_rabbit.log

If you wish to see the logs in your screen, spawn a new terminal and run:

$ python receive_logs.py

And of course, to emit logs type:

$ python emit_log.py

Using rabbitmqctl list_bindings You can verify that the code actually creates bindings and queues as we want. With the receive_logs.py programs running you should see something like:

$ sudo rabbitmqctl list_bindingslisting bindings ... logs    exchange        AMQ.GEN-JZTY20BRGKO-HJMUJJ0WLG  queue           []logs    Exchange        amq.gen-vso0pvvyiril2wov3i48yg  queue           []...done. 

RABBITMQ Use (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.