Rabbitmq method of Use (i)

Source: Internet
Author: User

  • Introduction

    RabbitMQ is a message broker. The principal idea was pretty simple: it accepts and forwards messages.

    RabbitMQ, and messaging in general, uses some jargon.

    • producing means nothing more than sending. sends messages is a producer. We'll draw it like this, with "P":

    • a queue is the name for a mailbox. It lives inside RabbitMQ. Although messages flow through RabbitMQ and your applications, they can is stored only inside a queue. A queue is not bound by any limits, it can store as many messages as what? It ' s essentially an infinite buffer. Many producers can send messages that go to one queue, many consumers can try to receive data from one queue< /c3>. A queue would be drawn as like that, with its name above it:

    • Consuming has a similar meaning to receiving. A consumer is a program this mostly waits to receive messages. On our drawings it's shown with "C":

    Note that the producer, consumer, and brokerdoes not have a to reside on the same machine; Indeed in the most applications they don ' t.

    Hello world! (using the Pika 0.9.8 Python client)

    Our "Hello World" won ' t is too complex? Let's send a message, receive it and print it on the screen. To doing so we need the programs:one that sends a message and one that receives and prints it.

    Our overall design would look like:

    Producer sends messages to the "Hello" queue. The consumer receives messages from that queue.

  • Sending

    Our first program send.py would send a single message to the queue. The first thing we need to the establish a connection with RabbitMQ server.

    1 # !/usr/bin/env python 2 Import Pika 3 4 connection = Pika. Blockingconnection (Pika. Connectionparameters (5                'localhost'))6 channel = Connection.channel ()

    We ' re connected now, to a broker on the local machine-hence the localhost. If We wanted to connect to a broker in a different machine we ' d simply specify the IT name or IP address here.

    Next, before sending we need to make sure the recipient queue exists. If we send a message to non-existing location, RabbitMQ'll just trash the message. Let's create a queue to which the message would be delivered and let's name it Hello:

    1 channel.queue_declare (queue='hello')

    At the point we ' re ready to send a message. Our first message would just contain a string Hello world! and we want to send it to our Hello queue.

    in RabbitMQ a message can never is sent directly to the queue, it always needs to go through an exchange . But let's not get dragged down by the details? You can read further about the exchanges  in the Third part of the This tutorial. All the We need to know are now, and use a the default exchange identified by an empty string. This exchange is special? It allows us to specify exactly to which queue the message should go. The queue name needs to being specified in The routing_key parameter:

    1 channel.basic_publish (exchange=",2                       routing_key='Hello  ',3                       body='Hello world! ' )4print"  [x] Sent ' Hello world! ' "

    Before exiting the program we need to make sure the network buffers were flushed and our message is actually delivered to RabbitMQ. We can do it by gently closing the connection.

    1 connection.close ()



    Receiving

    Our second program receive.py would receive messages from the queue and print them on the screen.

    Again, first we need to connect to RabbitMQ server. The code responsible for connecting to Rabbit are the same as previously.

    The next step, just like before, was to do sure that the queue exists. Creating a queue using Queue_declare is idempotent? we can run the command as many times as we do, and only one would be created.

    1 channel.queue_declare (queue='hello')

    Receiving messages from the queue are more complex. It works by subscribing a callback function to a queue. whenever we receive a message, this callback function is called by the Pika library. The This function would print on the screen the contents of the message.

    1 def Callback (ch, method, properties, body): 2     Print " [x] Received%r" % (body,)

    Next, we need to tell RabbitMQ the this particular callback function should receive messages from our Hello queu E:

    1 Channel.basic_consume (Callback,2                       queue='hello',3                        no_ack=true)

    For the command to succeed we must is sure that a queue which we want to subscribe to exists. Fortunately we ' re confident about that? We ' ve created a queue above? Usingqueue_declare.

    The no_ack parameter is described later on. and finally, we enter a never-ending loop, waits for data and runs callbacks whenever necessary.

  • 1 Print ' [*] waiting for messages. To exit Press CTRL + C'2 channel.start_consuming ()

    Putting it all together

    Full code for send.py:

     
    1 #!/usr/bin/env python2 ImportPika3 4Connection =Pika. Blockingconnection (Pika. Connectionparameters (5host='localhost'))6Channel =Connection.channel ()7 8Channel.queue_declare (queue='Hello')9 TenChannel.basic_publish (exchange="', Onerouting_key='Hello', Abody='Hello world!') - Print "[x] Sent ' Hello world! '" -Connection.close ()


    (send.py Source)

    Full receive.py code:

     
    1 #!/usr/bin/env python2 ImportPika3 4Connection =Pika. Blockingconnection (Pika. Connectionparameters (5host='localhost'))6Channel =Connection.channel ()7 8Channel.queue_declare (queue='Hello')9 Ten Print '[*] waiting for messages. To exit Press CTRL + C' One  A defCallback (ch, method, properties, body): -     Print "[x] Received%r"%(body,) -  the Channel.basic_consume (Callback, -Queue='Hello', -no_ack=True) -  +Channel.start_consuming ()


    (receive.py Source)

Rabbitmq method of Use (i)

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.