Created
February 15, 2022 20:29
-
-
Save lukebakken/b0a6852a7030303370f2259f687c0662 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Basic message consumer example""" | |
import functools | |
import logging | |
import pika | |
LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) ' | |
'-35s %(lineno) -5d: %(message)s') | |
LOGGER = logging.getLogger(__name__) | |
logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT) | |
def on_message(chan, method_frame, _header_frame, body, userdata=None): | |
"""Called when a message is received. Log message and ack it.""" | |
LOGGER.info('Userdata: %s Message body: %s', userdata, body) | |
chan.basic_ack(delivery_tag=method_frame.delivery_tag) | |
def main(): | |
"""Main method.""" | |
credentials = pika.PlainCredentials('guest', 'guest') | |
props = { 'connection_name' : 'https://stackoverflow.com/q/58275505/1466825' } | |
parameters = pika.ConnectionParameters('localhost', credentials=credentials, client_properties=props) | |
connection = pika.BlockingConnection(parameters) | |
channel = connection.channel() | |
channel.exchange_declare( | |
exchange='test_exchange', | |
exchange_type='direct', | |
passive=False, | |
durable=True, | |
auto_delete=False) | |
channel.queue_declare(queue='standard', auto_delete=True) | |
channel.queue_bind( | |
queue='standard', exchange='test_exchange', routing_key='standard_key') | |
channel.basic_qos(prefetch_count=1) | |
on_message_callback = functools.partial( | |
on_message, userdata='on_message_userdata') | |
channel.basic_consume('standard', on_message_callback) | |
try: | |
channel.start_consuming() | |
except KeyboardInterrupt: | |
channel.stop_consuming() | |
connection.close() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment