Skip to content

Instantly share code, notes, and snippets.

@kristoff-it
Last active September 18, 2019 13:40
Show Gist options
  • Save kristoff-it/42a91ed637d5f96b3450c303874641c2 to your computer and use it in GitHub Desktop.
Save kristoff-it/42a91ed637d5f96b3450c303874641c2 to your computer and use it in GitHub Desktop.
import asyncio
import aioredis
async def add_new_win(pool, winner):
# Creating tasks doesn't schedule them
# so you can create multiple and then
# schedule them all in one go using `gather`
task1 = pool.zincrby('wins_counter', 1, winner)
task2 = pool.incr('total_games_played')
await asyncio.gather(task1, task2)
async def main():
# Connect to Redis
pool = await aioredis.create_redis_pool('redis://localhost', encoding='utf8')
# Tail the event stream
last_id = '$'
while True:
events = await pool.xread(['wins_stream'], latest_ids=[last_id], timeout=0, count=10)
tasks = []
for _, e_id, e in events:
winner = e['winner']
# Again we don't actually schedule any task,
# and instead just prepare them
tasks.append(add_new_win(pool, winner))
last_id = e_id
# Notice the spread operator (`*tasks`), it
# allows using a single list as multiple arguments
# to a function call.
await asyncio.gather(*tasks)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
@kristoff-it
Copy link
Author

Hi Leonh, thank you for the correction, I've updated the code.
The problem with binary strings is solved by adding encoding=utf8 to the client connection constructor, while the second problem was definitely a mixup on my part when bouncing between aio-redis and redis-py.

Thanks again for the correction!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment