first commit
This commit is contained in:
80
layers/infrastructure/redis_connection.py
Normal file
80
layers/infrastructure/redis_connection.py
Normal file
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
Redis connection management and operations
|
||||
Infrastructure Layer - handles Redis connectivity and low-level operations
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
from typing import Optional, Dict, Any
|
||||
import logging
|
||||
import redis.asyncio as redis
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class RedisConnection:
|
||||
"""Manages Redis connection and basic operations"""
|
||||
|
||||
def __init__(self):
|
||||
self.redis_client: Optional[redis.Redis] = None
|
||||
self._host = os.getenv("REDIS_HOST", "localhost")
|
||||
self._port = int(os.getenv("REDIS_PORT", "6379"))
|
||||
self._db = int(os.getenv("REDIS_DB", "0"))
|
||||
|
||||
async def connect(self) -> None:
|
||||
"""Connect to Redis"""
|
||||
try:
|
||||
self.redis_client = redis.Redis(
|
||||
host=self._host,
|
||||
port=self._port,
|
||||
db=self._db,
|
||||
decode_responses=True
|
||||
)
|
||||
await self.redis_client.ping()
|
||||
logger.info("Successfully connected to Redis")
|
||||
except Exception as e:
|
||||
logger.error(f"Error connecting to Redis: {e}")
|
||||
raise
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
"""Disconnect from Redis"""
|
||||
if self.redis_client:
|
||||
await self.redis_client.close()
|
||||
logger.info("Disconnected from Redis")
|
||||
|
||||
async def get_client(self) -> redis.Redis:
|
||||
"""Get Redis client instance"""
|
||||
if not self.redis_client:
|
||||
await self.connect()
|
||||
return self.redis_client
|
||||
|
||||
async def set_with_expiry(self, key: str, value: str, expire_seconds: int = 3600) -> None:
|
||||
"""Set a key-value pair with expiration"""
|
||||
client = await self.get_client()
|
||||
await client.setex(key, expire_seconds, value)
|
||||
|
||||
async def get(self, key: str) -> Optional[str]:
|
||||
"""Get value by key"""
|
||||
client = await self.get_client()
|
||||
return await client.get(key)
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
"""Delete a key"""
|
||||
client = await self.get_client()
|
||||
await client.delete(key)
|
||||
|
||||
async def get_keys_by_pattern(self, pattern: str) -> list:
|
||||
"""Get keys matching a pattern"""
|
||||
client = await self.get_client()
|
||||
return await client.keys(pattern)
|
||||
|
||||
async def publish(self, channel: str, message: str) -> None:
|
||||
"""Publish message to a channel"""
|
||||
client = await self.get_client()
|
||||
await client.publish(channel, message)
|
||||
|
||||
async def create_pubsub(self) -> redis.client.PubSub:
|
||||
"""Create a pub/sub instance"""
|
||||
client = await self.get_client()
|
||||
return client.pubsub()
|
||||
|
||||
# Global Redis connection instance
|
||||
redis_connection = RedisConnection()
|
||||
Reference in New Issue
Block a user