Created
January 27, 2019 18:26
-
-
Save Ananto30/4ed90b5d593cdf5a496bbaec4450ed0c to your computer and use it in GitHub Desktop.
An example of Redis pub/sub in Python using asyncio_redis and async python programming
This file contains 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
import asyncio_redis | |
import asyncio | |
channels = ['channel1', 'weather'] | |
async def start(): | |
connection = await asyncio_redis.Connection.create(host='127.0.0.1', port=6379) | |
subscriber = await connection.start_subscribe() | |
await subscriber.subscribe(channels) | |
print('Connection opened') | |
print('Subscribed to channels {}'.format(channels)) | |
try: | |
await asyncio.gather(handle_redis(subscriber)) | |
except Exception as e: | |
import traceback | |
traceback.print_exc() | |
finally: | |
print('Connection closed') | |
async def handle_redis(subscriber): | |
while True: | |
msg_redis = await subscriber.next_published() | |
if msg_redis: | |
on_msg_from_redis(msg_redis) | |
def on_msg_from_redis(msg_redis): | |
print("Received msg '{}' from channel '{}'".format(msg_redis.value, msg_redis.channel)) | |
loop = asyncio.new_event_loop() | |
asyncio.set_event_loop(loop) | |
result = loop.run_until_complete(start()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment