RabbitMQ : Multiple binding & Routing
RabbitMQ & Celery Tutorials
Installing RabbitMQ & Celery
Hello World RabbitMQ
Work Queues (Task Queues) : RabbitMQ
Exchanges - Publish/Subscribe : RabbitMQ
Multiple bindings - Routing : RabbitMQ
Queueing Messages using Celery with RabbitMQ Message Broker Server
In this chapter, we're going to direct only critical error messages to the log file, while still print all of the log messages on the console. In other words, we're going to add a feature that allows us to make it possible to subscribe only to a subset of the messages.
Picture from slides.com.
As we already know, the code syntax for binding the exchanges to the queues looks like this:
channel.queue_bind(exchange=exchange_name, queue=queue_name)
What the code is telling: I, "queue_name", am interested in the message from "exchange_name".
Bindings can take an extra routing_key parameter and we create a binding with a key like this:
channel.queue_bind(exchange=exchange_name, queue=queue_name, routing_key='black')
We're going to use a direct exchange instead of the fanout exchange we used in previous chapter. This direct exchange guides a message to go to the queues whose binding key exactly matches the routing key of the message.
With a setup in the picture above, a message published to the exchange with a routing key orange will be routed to Queue #1. Messages with a routing key of black or green will go to Queue #2. All other messages will be discarded.
The picture above shows an example of multiple binding: bind multiple queues (Queue #1 and Queue #2) with the same binding key (green). In this case, this direct exchange setup will behave like fanout and will broadcast the message to all the matching queues: a message with routing key green will be delivered to both Queues.
We'll use direct exchange for our logging system instead of fanout. We will supply the log severity as a routing key so that a receiver can select the severity ('info', 'warning', or 'error') it wants to receive.
Let's create an exchange first:
channel.exchange_declare(exchange='direct_logs', type='direct')
To send a message:
channel.basic_publish(exchange='direct_logs', routing_key=severity, body=message)
The only difference from the previous chapter: we're going to create a new binding for each severity we're interested in:
result = channel.queue_declare(exclusive=True) queue_name = result.method.queue for severity in severities: channel.queue_bind(exchange='direct_logs', queue=queue_name, routing_key=severity)
emit_log_direct.py:
#!/usr/bin/env python import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='direct_logs', type='direct') severity = sys.argv[1] if len(sys.argv) > 1 else 'info' message = ' '.join(sys.argv[2:]) or 'Hello World!' channel.basic_publish(exchange='direct_logs', routing_key=severity, body=message) print " [x] Sent %r:%r" % (severity, message) connection.close()
receive_logs_direct.py:
#!/usr/bin/env python import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='direct_logs', type='direct') result = channel.queue_declare(exclusive=True) queue_name = result.method.queue severities = sys.argv[1:] if not severities: print >> sys.stderr, "Usage: %s [info] [warning] [error]" % \ (sys.argv[0],) sys.exit(1) for severity in severities: channel.queue_bind(exchange='direct_logs', queue=queue_name, routing_key=severity) print ' [*] Waiting for logs. To exit press CTRL+C' def callback(ch, method, properties, body): print " [x] %r:%r" % (method.routing_key, body,) channel.basic_consume(callback, queue=queue_name, no_ack=True) channel.start_consuming()
To save only 'warning' and 'error' (and not 'info') log messages to a file, just open a console and type:
$ python receive_logs_direct.py warning error > logs_from_rabbit.log
to see all the log messages on our screen, open a new terminal and do:
$ python receive_logs_direct.py info warning error [*] Waiting for logs. To exit press CTRL+C
To emit an error log message, type:
$ python receive_logs_direct.py warning error > logs_from_rabbit.log
RabbitMQ & Celery Tutorials
Installing RabbitMQ & Celery
Hello World RabbitMQ
Work Queues (Task Queues) : RabbitMQ
Exchanges - Publish/Subscribe : RabbitMQ
Multiple bindings - Routing : RabbitMQ
Queueing Messages using Celery with RabbitMQ Message Broker Server
Python tutorial
Python Home
Introduction
Running Python Programs (os, sys, import)
Modules and IDLE (Import, Reload, exec)
Object Types - Numbers, Strings, and None
Strings - Escape Sequence, Raw String, and Slicing
Strings - Methods
Formatting Strings - expressions and method calls
Files and os.path
Traversing directories recursively
Subprocess Module
Regular Expressions with Python
Regular Expressions Cheat Sheet
Object Types - Lists
Object Types - Dictionaries and Tuples
Functions def, *args, **kargs
Functions lambda
Built-in Functions
map, filter, and reduce
Decorators
List Comprehension
Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism
Hashing (Hash tables and hashlib)
Dictionary Comprehension with zip
The yield keyword
Generator Functions and Expressions
generator.send() method
Iterators
Classes and Instances (__init__, __call__, etc.)
if__name__ == '__main__'
argparse
Exceptions
@static method vs class method
Private attributes and private methods
bits, bytes, bitstring, and constBitStream
json.dump(s) and json.load(s)
Python Object Serialization - pickle and json
Python Object Serialization - yaml and json
Priority queue and heap queue data structure
Graph data structure
Dijkstra's shortest path algorithm
Prim's spanning tree algorithm
Closure
Functional programming in Python
Remote running a local file using ssh
SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table
SQLite 3 - B. Selecting, updating and deleting data
MongoDB with PyMongo I - Installing MongoDB ...
Python HTTP Web Services - urllib, httplib2
Web scraping with Selenium for checking domain availability
REST API : Http Requests for Humans with Flask
Blog app with Tornado
Multithreading ...
Python Network Programming I - Basic Server / Client : A Basics
Python Network Programming I - Basic Server / Client : B File Transfer
Python Network Programming II - Chat Server / Client
Python Network Programming III - Echo Server using socketserver network framework
Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn
Python Coding Questions I
Python Coding Questions II
Python Coding Questions III
Python Coding Questions IV
Python Coding Questions V
Python Coding Questions VI
Python Coding Questions VII
Python Coding Questions VIII
Python Coding Questions IX
Python Coding Questions X
Image processing with Python image library Pillow
Python and C++ with SIP
PyDev with Eclipse
Matplotlib
Redis with Python
NumPy array basics A
NumPy Matrix and Linear Algebra
Pandas with NumPy and Matplotlib
Celluar Automata
Batch gradient descent algorithm
Longest Common Substring Algorithm
Python Unit Test - TDD using unittest.TestCase class
Simple tool - Google page ranking by keywords
Google App Hello World
Google App webapp2 and WSGI
Uploading Google App Hello World
Python 2 vs Python 3
virtualenv and virtualenvwrapper
Uploading a big file to AWS S3 using boto module
Scheduled stopping and starting an AWS instance
Cloudera CDH5 - Scheduled stopping and starting services
Removing Cloud Files - Rackspace API with curl and subprocess
Checking if a process is running/hanging and stop/run a scheduled task on Windows
Apache Spark 1.3 with PySpark (Spark Python API) Shell
Apache Spark 1.2 Streaming
bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...
Flask app with Apache WSGI on Ubuntu14/CentOS7 ...
Fabric - streamlining the use of SSH for application deployment
Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App
Neural Networks with backpropagation for XOR using one hidden layer
NLP - NLTK (Natural Language Toolkit) ...
RabbitMQ(Message broker server) and Celery(Task queue) ...
OpenCV3 and Matplotlib ...
Simple tool - Concatenating slides using FFmpeg ...
iPython - Signal Processing with NumPy
iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github
iPython and Jupyter Notebook with Embedded D3.js
Downloading YouTube videos using youtube-dl embedded with Python
Machine Learning : scikit-learn ...
Django 1.6/1.8 Web Framework ...
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization