Broadcast Example¶
Let’s start off in the usual way and create a RabbitMQ communicator and subscribe to receive broadcasts.
[1]:
import kiwipy
comm = kiwipy.connect('amqp://127.0.0.1')
def subscriber(_comm, body, sender, subject, _corr_id):
print("Broadcast received:")
print("sender:\t{}\nsubject:{}\nbody:\t{}\n".format(
sender, subject, body))
sub_id = comm.add_broadcast_subscriber(subscriber)
Now, let’s broadcast!
[2]:
comm.broadcast_send(
body="You'll be making a delivery to Ebola 9 tomorrow",
sender="The Professor",
subject="Good news")
Broadcast received:
sender: The Professor
subject:Good news
body: You'll be making a delivery to Ebola 9 tomorrow
[2]:
True
True?! That doesn’t sound like good news.
No, no, that’s just the return value from broadcast_send
to tell you the message was indeed sent.
Ok, but it’s not exactly the kind of message I wanted to receive.
Sorry about that, here’s how to filter so you only get messages that you’re interested in.
Broadcast Filters¶
[3]:
# Remove the current subscriber
comm.remove_broadcast_subscriber(sub_id)
# Add a filtered one
filtered = kiwipy.BroadcastFilter(subscriber)
filtered.add_subject_filter("sell.*")
comm.add_broadcast_subscriber(filtered)
comm.broadcast_send(
'Tip-top caravan for sale',
"Bob Jones",
'sell.caravan')
Broadcast received:
sender: Bob Jones
subject:sell.caravan
body: Tip-top caravan for sale
[3]:
True
Hmm, I like me the look of that caravan. Ok, let’s send a purchase request back.
[4]:
comm.broadcast_send(
'I need a caravan for me ma',
sender="Mickey O'Neil",
subject='purchase.caravan')
[4]:
True
You can see here we don’t get anything printed because we’re only listening for sell
orders.
Finally let’s close the communicator.
[5]:
comm.close()