Debian Codegraph @

docs/modules/adapters/index.rst

raw
1 Connection Adapters
2 ===================
3 Pika uses connection adapters to provide a flexible method for adapting pika's
4 core communication to different IOLoop implementations. In addition to asynchronous adapters, there is the :class:`BlockingConnection <pika.adapters.blocking_connection.BlockingConnection>` adapter that provides a more idiomatic procedural approach to using Pika.
5
6 Adapters
7 --------
8 .. toctree::
9 :glob:
10 :maxdepth: 1
11
12 blocking
13 select
14 asyncio
15 tornado
16 twisted
17 gevent
18
19 Requesting message acknowledgements from another thread
20 -------------------------------------------------------
21 The single-threaded usage constraint of an individual Pika connection adapter
22 instance may result in a dropped AMQP/stream connection due to AMQP heartbeat
23 timeout in consumers that take a long time to process an incoming message. A
24 common solution is to delegate processing of the incoming messages to another
25 thread, while the connection adapter's thread continues to service its I/O
26 loop's message pump, permitting AMQP heartbeats and other I/O to be serviced in
27 a timely fashion.
28
29 Messages processed in another thread may not be acknowledged directly from that
30 thread, since all accesses to the connection adapter instance must be from a
31 single thread, which is the thread running the adapter's I/O loop. This is
32 accomplished by requesting a callback to be executed in the adapter's
33 I/O loop thread. For example, the callback function's implementation might look
34 like this:
35
36 .. code :: python
37
38 def ack_message(channel, delivery_tag):
39 """Note that `channel` must be the same Pika channel instance via which
40 the message being acknowledged was retrieved (AMQP protocol constraint).
41 """
42 if channel.is_open:
43 channel.basic_ack(delivery_tag)
44 else:
45 # Channel is already closed, so we can't acknowledge this message;
46 # log and/or do something that makes sense for your app in this case.
47 pass
48
49 The code running in the other thread may request the ``ack_message()`` function
50 to be executed in the connection adapter's I/O loop thread using an
51 adapter-specific mechanism:
52
53 - ``pika.BlockingConnection`` abstracts its I/O loop from the application and
54 thus exposes ``pika.BlockingConnection.add_callback_threadsafe()``. Refer to
55 this method's docstring for additional information. For example:
56
57 .. code :: python
58
59 connection.add_callback_threadsafe(functools.partial(ack_message, channel, delivery_tag))
60
61 Please see the documentation of other adapters for their specific methods.
62
63 This threadsafe callback request mechanism may also be used to delegate
64 publishing of messages, etc., from a background thread to the connection
65 adapter's thread.
66
67 Connection recovery
68 -------------------
69
70 Pika requires connection recovery to be performed by the application code and
71 strives to make it a straightforward process.
72
73 Different connection adapters take different approaches to connection recovery.
74
75 For ``pika.BlockingConnection`` adapter exception handling can be used to check
76 for connection errors. Here is a very basic example:
77
78 .. code :: python
79
80 import pika
81
82 while True:
83 try:
84 connection = pika.BlockingConnection()
85 channel = connection.channel()
86 channel.basic_consume('test', on_message_callback)
87 channel.start_consuming()
88 # Don't recover if connection was closed by broker
89 except pika.exceptions.ConnectionClosedByBroker:
90 break
91 # Don't recover on channel errors
92 except pika.exceptions.AMQPChannelError:
93 break
94 # Recover on all other connection errors
95 except pika.exceptions.AMQPConnectionError:
96 continue
97
98 A similar example can be found in `examples/blocking_consume_recover_multiple_hosts.py`.
99
100 Generic operation retry libraries such as
101 `retry <https://github.com/invl/retry>`_ can be used. Decorators make it
102 possible to configure some additional recovery behaviours, like delays between
103 retries and limiting the number of retries:
104
105 .. code :: python
106
107 from retry import retry
108
109
110 @retry(pika.exceptions.AMQPConnectionError, delay=5, jitter=(1, 3))
111 def consume():
112 connection = pika.BlockingConnection()
113 channel = connection.channel()
114 channel.basic_consume('test', on_message_callback)
115
116 try:
117 channel.start_consuming()
118 # Don't recover connections closed by server
119 except pika.exceptions.ConnectionClosedByBroker:
120 pass
121
122
123 consume()
124
125
126 For asynchronous adapters, use ``on_close_callback`` to react to connection
127 failure events. This callback can be used to clean up and recover the
128 connection.
129
130 An example of recovery using ``on_close_callback`` can be found in
131 `examples/asynchronous_consumer_example.py`.