File: connecting_async.rst

package info (click to toggle)
python-pika 0.9.14-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,048 kB
  • ctags: 2,110
  • sloc: python: 10,046; makefile: 134
file content (49 lines) | stat: -rw-r--r-- 1,859 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
Connecting to RabbitMQ with Callback-Passing Style
==================================================

When you connect to RabbitMQ with an asynchronous adapter, you are writing event
oriented code. The connection adapter will block on the IOLoop that is watching
to see when pika should read data from and write data to RabbitMQ. Because you're
now blocking on the IOLoop, you will receive callback notifications when specific
events happen.

Example Code
------------
In the example, there are three steps that take place:

1. Setup the connection to RabbitMQ
2. Start the IOLoop
3. Once connected, the on_open method will be called by Pika with a handle to
   the connection. In this method, a new channel will be opened on the connection.
4. Once the channel is opened, you can do your other actions, whether they be
   publishing messages, consuming messages or other RabbitMQ related activities.::

    import pika

    # Step #3
    def on_open(connection):
        connection.channel(on_channel_open)

    # Step #4
    def on_channel_open(channel):
        channel.basic_publish('exchange_name',
                              'routing_key',
                              'Test Message',
                              pika.BasicProperties(content_type='text/plain',
                                                   type='example'))

    # Step #1: Connect to RabbitMQ
    connection = pika.SelectConnection(on_open_callback=on_open)

    try:
        # Step #2 - Block on the IOLoop
        connection.ioloop.start()

    # Catch a Keyboard Interrupt to make sure that the connection is closed cleanly
    except KeyboardInterrupt:

        # Gracefully close the connection
        connection.close()

        # Start the IOLoop again so Pika can communicate, it will stop on its own when the connection is closed
        connection.ioloop.start()