71 lines
2.1 KiB
Python
71 lines
2.1 KiB
Python
from typing import Optional
|
|
|
|
import redis
|
|
from redis import asyncio as aioredis
|
|
|
|
from app.conf.app_config import RedisConfig, app_config
|
|
|
|
|
|
class RedisClientManager:
|
|
def __init__(self, config: RedisConfig):
|
|
self.config = config
|
|
self._client: Optional[aioredis.Redis] = None
|
|
self._sync_client: Optional[redis.Redis] = None
|
|
|
|
def init(self):
|
|
self._client = aioredis.from_url(
|
|
f"redis://{self.config.host}:{self.config.port}",
|
|
password=self.config.password if self.config.password else None,
|
|
db=self.config.db,
|
|
decode_responses=self.config.decode_responses,
|
|
socket_timeout=10,
|
|
socket_connect_timeout=10
|
|
)
|
|
self._sync_client = redis.Redis(
|
|
host=self.config.host,
|
|
port=self.config.port,
|
|
password=self.config.password if self.config.password else None,
|
|
db=self.config.db,
|
|
decode_responses=self.config.decode_responses,
|
|
socket_timeout=10,
|
|
socket_connect_timeout=10
|
|
)
|
|
|
|
@property
|
|
def client(self) -> aioredis.Redis:
|
|
if self._client is None:
|
|
self.init()
|
|
return self._client
|
|
|
|
@property
|
|
def sync_client(self) -> redis.Redis:
|
|
if self._sync_client is None:
|
|
self.init()
|
|
return self._sync_client
|
|
|
|
async def close(self):
|
|
if self._client:
|
|
await self._client.close()
|
|
if self._sync_client:
|
|
self._sync_client.close()
|
|
|
|
|
|
redis_client_manager = RedisClientManager(app_config.redis)
|
|
|
|
if __name__ == '__main__':
|
|
import asyncio
|
|
|
|
redis_client_manager.init()
|
|
|
|
async def test():
|
|
await redis_client_manager.client.set("test_key", "test_value")
|
|
value = await redis_client_manager.client.get("test_key")
|
|
print(f"Async get: {value}")
|
|
|
|
redis_client_manager.sync_client.set("sync_test_key", "sync_test_value")
|
|
sync_value = redis_client_manager.sync_client.get("sync_test_key")
|
|
print(f"Sync get: {sync_value}")
|
|
|
|
await redis_client_manager.close()
|
|
|
|
asyncio.run(test()) |