Integrate Redis (10.30.20.70) for locks, cache, and decision state to maximize infra utilization
This commit is contained in:
42
services.py
42
services.py
@@ -3,8 +3,50 @@ import random
|
||||
import time
|
||||
import uuid
|
||||
import requests
|
||||
import redis
|
||||
from config import settings
|
||||
|
||||
_redis = None
|
||||
|
||||
def redis_client():
|
||||
global _redis
|
||||
if _redis is None:
|
||||
try:
|
||||
_redis = redis.Redis.from_url(settings.redis_url, decode_responses=True, socket_timeout=2)
|
||||
_redis.ping()
|
||||
except Exception:
|
||||
_redis = None
|
||||
return _redis
|
||||
|
||||
def redis_set_json(key: str, value: dict, ttl: int = 3600):
|
||||
r = redis_client()
|
||||
if not r:
|
||||
return False
|
||||
try:
|
||||
r.setex(key, ttl, json.dumps(value))
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def redis_get_json(key: str):
|
||||
r = redis_client()
|
||||
if not r:
|
||||
return None
|
||||
try:
|
||||
v = r.get(key)
|
||||
return json.loads(v) if v else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def redis_lock(key: str, ttl: int = 180):
|
||||
r = redis_client()
|
||||
if not r:
|
||||
return True
|
||||
try:
|
||||
return bool(r.set(key, str(int(time.time())), ex=ttl, nx=True))
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
|
||||
def _ollama_generate(model: str, payload_obj: dict, timeout: int = 45):
|
||||
payload = {"model": model, "stream": False, "prompt": json.dumps(payload_obj), "format": "json"}
|
||||
|
||||
Reference in New Issue
Block a user