File: connecting_async.rst

package info (click to toggle)
python-pika 1.3.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,064 kB
  • sloc: python: 20,886; makefile: 136
file content (52 lines) | stat: -rw-r--r-- 2,028 bytes parent folder | download | duplicates (2)
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
50
51
52
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_open_callback=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'))

    def on_close(connection, exception):
        # Invoked when the connection is closed
        connection.ioloop.stop()

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

    try:
        # Step #2 - Start and 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 when on_close is called
        connection.ioloop.start()