| 1 |
.. _tutorial: |
| 2 |
|
| 3 |
######## |
| 4 |
Tutorial |
| 5 |
######## |
| 6 |
|
| 7 |
============ |
| 8 |
Hello World! |
| 9 |
============ |
| 10 |
|
| 11 |
Tradition dictates that we start with hello world! However rather than |
| 12 |
simply striving for the shortest program possible, we'll aim for a |
| 13 |
more illustrative example while still restricting the functionality to |
| 14 |
sending and receiving a single message. |
| 15 |
|
| 16 |
.. literalinclude:: ../examples/helloworld.py |
| 17 |
:lines: 21- |
| 18 |
:linenos: |
| 19 |
|
| 20 |
You can see the import of :py:class:`~proton.reactor.Container` from ``proton.reactor`` on the |
| 21 |
second line. This is a class that makes programming with proton a |
| 22 |
little easier for the common cases. It includes within it an event |
| 23 |
loop, and programs written using this utility are generally structured |
| 24 |
to react to various events. This reactive style is particularly suited |
| 25 |
to messaging applications. |
| 26 |
|
| 27 |
To be notified of a particular event, you define a class with the |
| 28 |
appropriately named method on it. That method is then called by the |
| 29 |
event loop when the event occurs. |
| 30 |
|
| 31 |
We define a class here, ``HelloWorld``, which handles the key events of |
| 32 |
interest in sending and receiving a message. |
| 33 |
|
| 34 |
The ``on_start()`` method is called when the event loop first |
| 35 |
starts. We handle that by establishing our connection (line 13), a |
| 36 |
sender over which to send the message (line 15) and a receiver over |
| 37 |
which to receive it back again (line 14). |
| 38 |
|
| 39 |
The ``on_sendable()`` method is called when message can be transferred |
| 40 |
over the associated sender link to the remote peer. We send out our |
| 41 |
``Hello World!`` message (line 18), then close the sender (line 19) as |
| 42 |
we only want to send one message. The closing of the sender will |
| 43 |
prevent further calls to ``on_sendable()``. |
| 44 |
|
| 45 |
The ``on_message()`` method is called when a message is |
| 46 |
received. Within that we simply print the body of the message (line |
| 47 |
22) and then close the connection (line 23). |
| 48 |
|
| 49 |
Now that we have defined the logic for handling these events, we |
| 50 |
create an instance of a :py:class:`~proton.reactor.Container`, pass it |
| 51 |
our handler and then enter the event loop by calling |
| 52 |
:py:meth:`~proton.reactor.Container.run()`. At this point, control |
| 53 |
passes to the container instance, which will make the appropriate |
| 54 |
callbacks to any defined handlers. |
| 55 |
|
| 56 |
To run the example, you will need to have a broker (or similar) |
| 57 |
accepting connections on that url either with a queue (or topic) |
| 58 |
matching the given address or else configured to create such a queue |
| 59 |
(or topic) dynamically. There is a simple broker.py script included |
| 60 |
alongside the examples that can be used for this purpose if |
| 61 |
desired. (It is also written using the API described here, and as such |
| 62 |
gives an example of a slightly more involved application). |
| 63 |
|
| 64 |
==================== |
| 65 |
Hello World, Direct! |
| 66 |
==================== |
| 67 |
|
| 68 |
Though often used in conjunction with a broker, AMQP does not |
| 69 |
*require* this. It also allows senders and receivers to communicate |
| 70 |
directly if desired. |
| 71 |
|
| 72 |
Let's modify our example to demonstrate this. |
| 73 |
|
| 74 |
.. literalinclude:: ../examples/helloworld_direct.py |
| 75 |
:lines: 21- |
| 76 |
:emphasize-lines: 12,22-23,25-26 |
| 77 |
:linenos: |
| 78 |
|
| 79 |
The first difference, on line 12, is that rather than creating a |
| 80 |
receiver on the same connection as our sender, we listen for incoming |
| 81 |
connections by invoking the |
| 82 |
:py:meth:`~proton.reactor.Container.listen()` method on the |
| 83 |
container. |
| 84 |
|
| 85 |
As we only need then to initiate one link, the sender, we can do that |
| 86 |
by passing in a url rather than an existing connection, and the |
| 87 |
connection will also be automatically established for us. |
| 88 |
|
| 89 |
We send the message in response to the ``on_sendable()`` callback and |
| 90 |
print the message out in response to the ``on_message()`` callback |
| 91 |
exactly as before. |
| 92 |
|
| 93 |
However we also handle two new events. We now close the connection |
| 94 |
from the senders side once the message has been accepted (line |
| 95 |
23). The acceptance of the message is an indication of successful |
| 96 |
transfer to the peer. We are notified of that event through the |
| 97 |
``on_accepted()`` callback. Then, once the connection has been closed, |
| 98 |
of which we are notified through the ``on_closed()`` callback, we stop |
| 99 |
accepting incoming connections (line 26) at which point there is no |
| 100 |
work to be done and the event loop exits, and the run() method will |
| 101 |
return. |
| 102 |
|
| 103 |
So now we have our example working without a broker involved! |
| 104 |
|
| 105 |
============================= |
| 106 |
Asynchronous Send and Receive |
| 107 |
============================= |
| 108 |
|
| 109 |
Of course, these ``HelloWorld!`` examples are very artificial, |
| 110 |
communicating as they do over a network connection but with the same |
| 111 |
process. A more realistic example involves communication between |
| 112 |
separate processes (which could indeed be running on completely |
| 113 |
separate machines). |
| 114 |
|
| 115 |
Let's separate the sender from the receiver, and let's transfer more than |
| 116 |
a single message between them. |
| 117 |
|
| 118 |
We'll start with a simple sender. |
| 119 |
|
| 120 |
.. literalinclude:: ../examples/simple_send.py |
| 121 |
:lines: 21- |
| 122 |
:linenos: |
| 123 |
|
| 124 |
As with the previous example, we define the application logic in a |
| 125 |
class that handles various events. As before, we use the |
| 126 |
``on_start()`` event to establish our sender link over which we will |
| 127 |
transfer messages and the ``on_sendable()`` event to know when we can |
| 128 |
transfer our messages. |
| 129 |
|
| 130 |
Because we are transferring more than one message, we need to keep |
| 131 |
track of how many we have sent. We'll use a ``sent`` member variable |
| 132 |
for that. The ``total`` member variable will hold the number of |
| 133 |
messages we want to send. |
| 134 |
|
| 135 |
AMQP defines a credit-based flow control mechanism. Flow control |
| 136 |
allows the receiver to control how many messages it is prepared to |
| 137 |
receive at a given time and thus prevents any component being |
| 138 |
overwhelmed by the number of messages it is sent. |
| 139 |
|
| 140 |
In the ``on_sendable()`` callback, we check that our sender has credit |
| 141 |
before sending messages. We also check that we haven't already sent |
| 142 |
the required number of messages. |
| 143 |
|
| 144 |
The ``send()`` call on line 21 is of course asynchronous. When it |
| 145 |
returns, the message has not yet actually been transferred across the |
| 146 |
network to the receiver. By handling the ``on_accepted()`` event, we |
| 147 |
can get notified when the receiver has received and accepted the |
| 148 |
message. In our example we use this event to track the confirmation of |
| 149 |
the messages we have sent. We only close the connection and exit when |
| 150 |
the receiver has received all the messages we wanted to send. |
| 151 |
|
| 152 |
If we are disconnected after a message is sent and before it has been |
| 153 |
confirmed by the receiver, it is said to be ``in doubt``. We don't |
| 154 |
know whether or not it was received. In this example, we will handle |
| 155 |
that by resending any in-doubt messages. This is known as an |
| 156 |
'at-least-once' guarantee, since each message should eventually be |
| 157 |
received at least once, though a given message may be received more |
| 158 |
than once (i.e. duplicates are possible). In the ``on_disconnected()`` |
| 159 |
callback, we reset the sent count to reflect only those that have been |
| 160 |
confirmed. The library will automatically try to reconnect for us, and |
| 161 |
when our sender is sendable again, we can restart from the point we |
| 162 |
know the receiver got to. |
| 163 |
|
| 164 |
Now let's look at the corresponding receiver: |
| 165 |
|
| 166 |
.. literalinclude:: ../examples/simple_recv.py |
| 167 |
:lines: 21- |
| 168 |
:linenos: |
| 169 |
|
| 170 |
Here we handle the ``on_start()`` by creating our receiver, much like |
| 171 |
we did for the sender. We also handle the ``on_message()`` event for |
| 172 |
received messages and print the message out as in the ``Hello World!`` |
| 173 |
examples. However, we add some logic to allow the receiver to wait for |
| 174 |
a given number of messages, then close the connection and exit. We |
| 175 |
also add some logic to check for and ignore duplicates, using a simple |
| 176 |
sequential id scheme. |
| 177 |
|
| 178 |
Again, though sending between these two examples requires some sort of |
| 179 |
intermediary process (e.g. a broker), AMQP allows us to send messages |
| 180 |
directly between two processes without this if we so wish. In that |
| 181 |
case, one of the processes needs to accept incoming socket connections. |
| 182 |
Let's create a modified version of the receiving example that does this: |
| 183 |
|
| 184 |
.. literalinclude:: ../examples/direct_recv.py |
| 185 |
:lines: 21- |
| 186 |
:emphasize-lines: 14,26 |
| 187 |
:linenos: |
| 188 |
|
| 189 |
There are only two differences here. On line 14, instead of initiating |
| 190 |
a link (and implicitly a connection), we listen for incoming |
| 191 |
connections. On line 26, when we have received all the expected |
| 192 |
messages, we then stop listening for incoming connections by closing |
| 193 |
the listener object. |
| 194 |
|
| 195 |
You can use the original send example now to send to this receiver |
| 196 |
directly. (Note: you will need to stop any broker that is listening on |
| 197 |
the 5672 port, or else change the port used by specifying a different |
| 198 |
address to each example via the -a command line switch). |
| 199 |
|
| 200 |
We could also modify the original sender to allow the original |
| 201 |
receiver to connect to it. Again, that just requires two modifications: |
| 202 |
|
| 203 |
.. literalinclude:: ../examples/direct_send.py |
| 204 |
:lines: 21- |
| 205 |
:emphasize-lines: 16,29 |
| 206 |
:linenos: |
| 207 |
|
| 208 |
As with the modified receiver, instead of initiating establishment of |
| 209 |
a link, we listen for incoming connections on line 16 and then on line |
| 210 |
29, when we have received confirmation of all the messages we sent, we |
| 211 |
can close the listener in order to exit. The symmetry in the |
| 212 |
underlying AMQP that enables this is quite unique and elegant, and in |
| 213 |
reflecting this the proton API provides a flexible toolkit for |
| 214 |
implementing all sorts of interesting intermediaries (the broker.py |
| 215 |
script provided as a simple broker for testing purposes provides an |
| 216 |
example of this). |
| 217 |
|
| 218 |
To try this modified sender, run the original receiver against it. |
| 219 |
|
| 220 |
================ |
| 221 |
Request/Response |
| 222 |
================ |
| 223 |
|
| 224 |
A common pattern is to send a request message and expect a response |
| 225 |
message in return. AMQP has special support for this pattern. Let's |
| 226 |
have a look at a simple example. We'll start with the 'server', |
| 227 |
i.e. the program that will process the request and send the |
| 228 |
response. Note that we are still using a broker in this example. |
| 229 |
|
| 230 |
Our server will provide a very simple service: it will respond with |
| 231 |
the body of the request converted to uppercase. |
| 232 |
|
| 233 |
.. literalinclude:: ../examples/server.py |
| 234 |
:lines: 21- |
| 235 |
:linenos: |
| 236 |
|
| 237 |
The code here is not too different from the simple receiver |
| 238 |
example. When we receive a request however, we look at the |
| 239 |
:py:attr:`~proton.Message.reply_to` address on the |
| 240 |
:py:class:`~proton.Message` and create a sender for that over which to |
| 241 |
send the response. We'll cache the senders in case we get further |
| 242 |
requests with the same reply_to. |
| 243 |
|
| 244 |
Now let's create a simple client to test this service out. |
| 245 |
|
| 246 |
.. literalinclude:: ../examples/client.py |
| 247 |
:lines: 21- |
| 248 |
:linenos: |
| 249 |
|
| 250 |
As well as sending requests, we need to be able to get back the |
| 251 |
responses. We create a receiver for that (see line 15), but we don't |
| 252 |
specify an address, we set the dynamic option which tells the broker |
| 253 |
to create a temporary address over which we can receive our responses. |
| 254 |
|
| 255 |
We need to use the address allocated by the broker as the reply_to |
| 256 |
address of our requests, so we can't send them until the broker has |
| 257 |
confirmed our receiving link has been set up (at which point we will |
| 258 |
have our allocated address). To do that, we add an |
| 259 |
``on_link_opened()`` method to our handler class, and if the link |
| 260 |
associated with the event is the receiver, we use that as the trigger to |
| 261 |
send our first request. |
| 262 |
|
| 263 |
Again, we could avoid having any intermediary process here if we |
| 264 |
wished. The following code implementas a server to which the client |
| 265 |
above could connect directly without any need for a broker or similar. |
| 266 |
|
| 267 |
.. literalinclude:: ../examples/server_direct.py |
| 268 |
:lines: 21- |
| 269 |
:linenos: |
| 270 |
|
| 271 |
Though this requires some more extensive changes than the simple |
| 272 |
sending and receiving examples, the essence of the program is still |
| 273 |
the same. Here though, rather than the server establishing a link for |
| 274 |
the response, it relies on the link that the client established, since |
| 275 |
that now comes in directly to the server process. |
| 276 |
|
| 277 |
Miscellaneous |
| 278 |
============= |
| 279 |
|
| 280 |
Many brokers offer the ability to consume messages based on a |
| 281 |
'selector' that defines which messages are of interest based on |
| 282 |
particular values of the headers. The following example shows how that |
| 283 |
can be achieved: |
| 284 |
|
| 285 |
.. literalinclude:: ../examples/selected_recv.py |
| 286 |
:lines: 21- |
| 287 |
:emphasize-lines: 16 |
| 288 |
:linenos: |
| 289 |
|
| 290 |
When creating the receiver, we specify a Selector object as an |
| 291 |
option. The options argument can take a single object or a |
| 292 |
list. Another option that is sometimes of interest when using a broker |
| 293 |
is the ability to 'browse' the messages on a queue, rather than |
| 294 |
consuming them. This is done in AMQP by specifying a distribution mode |
| 295 |
of 'copy' (instead of 'move' which is the expected default for |
| 296 |
queues). An example of that is shown next: |
| 297 |
|
| 298 |
.. literalinclude:: ../examples/queue_browser.py |
| 299 |
:lines: 21- |
| 300 |
:emphasize-lines: 11 |
| 301 |
:linenos: |