🎯 Redis 기반 캐싱 적용 보고서

📌 목적

오디오 분석 과정에서 반복적으로 MinIO에서 features.json을 불러오는 연산을 줄이고, 캐시 기반 성능 최적화를 달성하기 위함. 특히 Celery 분산 환경에서도 다중 작업자가 캐시를 공유할 수 있도록 Redis를 캐싱 백엔드로 도입.


✅ 시스템 구성도 요약

[MinIO (features.json)]
          ↓ (1회 조회)
     [Redis 캐시]
          ↓
     [Local Memory Cache]
          ↓
   오디오 분석 모듈 (Celery Task)


🔧 구현 요소

1. .env 설정 (로컬 / 배포 공통)

# 예시 (development)
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_DB=0


2. Redis 캐시 유틸: redis_cache.py

import os, redis, json
from dotenv import load_dotenv

_feature_cache = {}

# 환경 변수 로드
env_path = "../../infra/env/.env.production.local" if os.getenv("ENV_MODE") == "production" else "../../infra/env/.env.development.local"
load_dotenv(dotenv_path=env_path)

# Redis 연결
redis_client = redis.StrictRedis(
    host=os.getenv("REDIS_HOST"),
    port=int(os.getenv("REDIS_PORT")),
    db=int(os.getenv("REDIS_DB")),
    decode_responses=True
)

def get_cache_feature(cache_key: str):
    if cache_key in _feature_cache:
        print(f"🧠 (local) 캐시 HIT: {cache_key}")
        return _feature_cache[cache_key]

    redis_val = redis_client.get(cache_key)
    if redis_val:
        try:
            data = json.loads(redis_val)
            _feature_cache[cache_key] = data
            print(f"🗃️ (redis) 캐시 HIT: {cache_key}")
            return data
        except Exception as e:
            print(f"❌ Redis JSON decode 실패: {e}")
    return None

def set_cache_feature(cache_key: str, data: dict, ttl_seconds=3600):
    _feature_cache[cache_key] = data
    redis_client.set(cache_key, json.dumps(data), ex=ttl_seconds)
    print(f"✅ Redis 캐시 저장: {cache_key}")


3. 분석 모듈 캐시 통합: audio_analysis.py

from redis_cache import get_cache_feature, set_cache_feature

def get_cached_features(song_id, instrument_id):
    cache_key = f"{song_id}:{instrument_id}"
    print(f"🚀 [get_cached_features] 호출됨 - key: {cache_key}")

    cached = get_cache_feature(cache_key)
    if cached:
        return cached

    print(f"📥 캐시 MISS: {cache_key} → MinIO에서 로드")
    features_json = load_json_from_minio(song_id, "features.json")

    if "instruments" not in features_json or instrument_id not in features_json["instruments"]:
        raise KeyError(f"features.json 내에 {instrument_id} 항목이 없습니다.")

    instrument_features = features_json["instruments"][instrument_id]
    set_cache_feature(cache_key, instrument_features)
    return instrument_features


🧪 테스트 로그 요약