|
| 1 | +from typing import Any, AsyncGenerator |
| 2 | + |
| 3 | +from redis.asyncio import RedisCluster |
| 4 | +from taskiq.abc.broker import AsyncBroker |
| 5 | +from taskiq.message import BrokerMessage |
| 6 | + |
| 7 | + |
| 8 | +class BaseRedisClusterBroker(AsyncBroker): |
| 9 | + """Base broker that works with Redis Cluster.""" |
| 10 | + |
| 11 | + def __init__( |
| 12 | + self, |
| 13 | + url: str, |
| 14 | + queue_name: str = "taskiq", |
| 15 | + max_connection_pool_size: int = 2**31, |
| 16 | + **connection_kwargs: Any, |
| 17 | + ) -> None: |
| 18 | + """ |
| 19 | + Constructs a new broker. |
| 20 | +
|
| 21 | + :param url: url to redis. |
| 22 | + :param queue_name: name for a list in redis. |
| 23 | + :param max_connection_pool_size: maximum number of connections in pool. |
| 24 | + :param connection_kwargs: additional arguments for aio-redis ConnectionPool. |
| 25 | + """ |
| 26 | + super().__init__() |
| 27 | + |
| 28 | + self.redis: RedisCluster[bytes] = RedisCluster.from_url( |
| 29 | + url=url, |
| 30 | + max_connections=max_connection_pool_size, |
| 31 | + **connection_kwargs, |
| 32 | + ) |
| 33 | + |
| 34 | + self.queue_name = queue_name |
| 35 | + |
| 36 | + async def shutdown(self) -> None: |
| 37 | + """Closes redis connection pool.""" |
| 38 | + await self.redis.aclose() # type: ignore[attr-defined] |
| 39 | + await super().shutdown() |
| 40 | + |
| 41 | + |
| 42 | +class ListQueueClusterBroker(BaseRedisClusterBroker): |
| 43 | + """Broker that works with Redis Cluster and distributes tasks between workers.""" |
| 44 | + |
| 45 | + async def kick(self, message: BrokerMessage) -> None: |
| 46 | + """ |
| 47 | + Put a message in a list. |
| 48 | +
|
| 49 | + This method appends a message to the list of all messages. |
| 50 | +
|
| 51 | + :param message: message to append. |
| 52 | + """ |
| 53 | + await self.redis.lpush(self.queue_name, message.message) # type: ignore[attr-defined] |
| 54 | + |
| 55 | + async def listen(self) -> AsyncGenerator[bytes, None]: |
| 56 | + """ |
| 57 | + Listen redis queue for new messages. |
| 58 | +
|
| 59 | + This function listens to the queue |
| 60 | + and yields new messages if they have BrokerMessage type. |
| 61 | +
|
| 62 | + :yields: broker messages. |
| 63 | + """ |
| 64 | + redis_brpop_data_position = 1 |
| 65 | + while True: |
| 66 | + value = await self.redis.brpop([self.queue_name]) # type: ignore[attr-defined] |
| 67 | + yield value[redis_brpop_data_position] |
0 commit comments