I have the following Python code:
import redis
from app.infra.services.notifications import INotifier
from app.schemas.notification import NotificationMessage
from app.config import settings
REDIS_CLIENT_PUBSUB = redis.StrictRedis(
host=settings.REDIS_HOST,
port=settings.REDIS_PORT,
password=settings.REDIS_PASSWORD,
)
class RedisNotifier(INotifier):
def __init__(self):
self.redis_client = REDIS_CLIENT_PUBSUB
async def send_notification(self, room: str, notification: NotificationMessage) -> None:
await self.redis_client.publish(room, notification.json())
redis_notifier = RedisNotifier()
I have a web application written in FastAPI that will use redis_notifier to post messages to channels. My question is if it really:
self.redis_client.publish(room, notification.json())
It is asynchronous, that is, my web application will be able to abandon this coroutine and do other things while publish is finished?
I’m a little confused with the redis and aioredis library, I don’t know if my code makes sense or I’m doing something wrong
2
Answers
Redis here is synchronous which means it blocks the execution your code till it completes the operation.
You may use aioredis. or asyncio-redis
https://aioredis.readthedocs.io/en/latest/
https://pypi.org/project/asyncio-redis/
aioredis last release is 2.0.1 and dates back to December 2021. aioredis was merged into redis-py 4.2.0rc1+, so it is possible to get it with a standard installation of redis-py.
Find examples here
https://redis-py.readthedocs.io/en/stable/examples/asyncio_examples.html