redis include + client with bis logic
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
import json
|
||||
from typing import Optional, Any
|
||||
import redis.asyncio as aioredis
|
||||
from src.shared.config import settings
|
||||
|
||||
|
||||
class RedisClient:
|
||||
def __init__(self, host: str, port: int):
|
||||
self.host = host or settings.REDIS_HOST
|
||||
self.port = port or settings.REDIS_PORT
|
||||
self._client: Optional[aioredis.Redis] = None
|
||||
|
||||
async def connect(self):
|
||||
if self._client is None:
|
||||
self._client = await aioredis.from_url(
|
||||
f"redis://{self.host}:{self.port}",
|
||||
encoding="utf-8",
|
||||
decode_responses=True
|
||||
)
|
||||
|
||||
async def disconnect(self):
|
||||
if self._client:
|
||||
await self._client.aclose()
|
||||
self._client = None
|
||||
|
||||
async def get(self, key: str) -> Optional[str]:
|
||||
if self._client is None:
|
||||
await self.connect()
|
||||
return await self._client.get(key)
|
||||
|
||||
async def set(self, key: str, value: str, ttl: Optional[int] = None):
|
||||
if self._client is None:
|
||||
await self.connect()
|
||||
if ttl:
|
||||
await self._client.setex(key, ttl, value)
|
||||
else:
|
||||
await self._client.set(key, value)
|
||||
|
||||
async def get_json(self, key: str) -> Optional[dict[str, Any]]:
|
||||
value = await self.get(key)
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return json.loads(value)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
|
||||
async def set_json(self, key: str, value: dict[str, Any], ttl: Optional[int] = None):
|
||||
json_str = json.dumps(value)
|
||||
await self.set(key, json_str, ttl)
|
||||
|
||||
async def delete(self, key: str):
|
||||
if self._client is None:
|
||||
await self.connect()
|
||||
await self._client.delete(key)
|
||||
|
||||
async def exists(self, key: str) -> bool:
|
||||
if self._client is None:
|
||||
await self.connect()
|
||||
return bool(await self._client.exists(key))
|
||||
|
||||
async def incr(self, key: str) -> int:
|
||||
if self._client is None:
|
||||
await self.connect()
|
||||
return await self._client.incr(key)
|
||||
|
||||
async def expire(self, key: str, seconds: int):
|
||||
if self._client is None:
|
||||
await self.connect()
|
||||
await self._client.expire(key, seconds)
|
||||
|
||||
async def keys(self, pattern: str) -> list[str]:
|
||||
if self._client is None:
|
||||
await self.connect()
|
||||
return await self._client.keys(pattern)
|
||||
|
||||
Reference in New Issue
Block a user