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):
    # Step #4
    def on_channel_open(channel):
                              'Test Message',
    def on_close(connection, exception):
        # Invoked when the connection is closed
    # Step #1: Connect to RabbitMQ
    connection = pika.SelectConnection(on_open_callback=on_open, on_close_callback=on_close)
        # Step #2 - Start and block on the IOLoop
    # Catch a Keyboard Interrupt to make sure that the connection is closed cleanly
    except KeyboardInterrupt:
        # Gracefully close the connection
        # Start the IOLoop again so Pika can communicate,
        # it will stop when on_close is called