Skip to main content

生产级 Python 异步缓存库,支持内存、文件(热重载)、Redis 后端

Project description

Symphra Cache

English | 中文

🚀 Production-grade async caching library for Python 3.11+

CI PyPI version Python versions License: MIT Code coverage

✨ Features

  • 🎯 Three Backends

    • Memory: High-performance in-memory cache with LRU eviction
    • File: Persistent SQLite-based cache with hot reload support
    • Redis: Distributed cache with cluster and sentinel support
  • ⚡ Performance

    • Fully async/await support
    • Memory backend: < 0.01ms latency
    • File backend: Hot reload 100k entries in < 5s
    • Redis backend: Connection pooling with hiredis acceleration
  • 🔒 Advanced Features

    • Distributed locks (Redis-based)
    • Cache warming and invalidation notifications
    • Prometheus/StatsD monitoring
    • Batch operations support
  • 🎨 Developer Friendly

    • Simple decorator API (@cached)
    • Context manager support (async with cache.lock())
    • Type hints everywhere
    • Comprehensive Chinese documentation

📦 Installation

# Basic installation (uv - recommended)
uv add symphra-cache

# Or with pip
pip install symphra-cache

# With Redis support
uv add symphra-cache redis

# Full installation (all features)
pip install symphra-cache[all]

Monitoring

from symphra_cache import CacheManager, CacheMonitor
from symphra_cache.monitoring.prometheus import PrometheusExporter
from symphra_cache.monitoring.statsd import StatsDExporter

# Enable monitoring
cache = CacheManager.from_config({"backend": "memory"})
monitor = CacheMonitor(cache)

# Do some operations
cache.set("user:1", {"name": "Alice"})
cache.get("user:1")

# Unified metrics API
metrics = monitor.metrics
print(metrics.get_latency_stats("get"))  # {"min": ..., "max": ..., "avg": ...}

# Prometheus text metrics
prom = PrometheusExporter(monitor, namespace="myapp", subsystem="cache")
print(prom.generate_metrics())

# StatsD exporter (requires reachable server if sending)
statsd = StatsDExporter(monitor, prefix="myapp.cache")
# await statsd.send_metrics()  # in async context
  • Install monitoring extras: pip install symphra-cache[monitoring]
  • Provides Prometheus/StatsD exporters with hit/miss, counts, and latency stats.

🚀 Quick Start

Basic Usage

from symphra_cache import CacheManager
from symphra_cache.backends import MemoryBackend

# Create cache manager with memory backend
cache = CacheManager(backend=MemoryBackend())

# Basic operations
cache.set("user:123", {"name": "Alice", "age": 30}, ttl=3600)
user = cache.get("user:123")

# Async operations
await cache.aset("product:456", {"name": "Laptop", "price": 999})
product = await cache.aget("product:456")

File Backend with Hot Reload

from symphra_cache.backends import FileBackend

# Create file backend (persists to SQLite)
backend = FileBackend(db_path="./cache.db")
cache = CacheManager(backend=backend)

# Set cache (persisted immediately)
cache.set("session:xyz", {"user_id": 123}, ttl=1800)

# Restart process... cache automatically reloads!
# The data is still available after restart
session = cache.get("session:xyz")  # ✅ Works!

Decorator API

from symphra_cache.decorators import acache

@acache(cache, ttl=300)
async def get_user_profile(user_id: int):
    """Fetch user profile (cached for 5 minutes)"""
    return await database.fetch_user(user_id)

# First call: queries database
profile = await get_user_profile(123)

# Second call: returns from cache
profile = await get_user_profile(123)  # ⚡ Fast!

Distributed Lock

from symphra_cache.backends import RedisBackend
from symphra_cache.locks import DistributedLock

cache = CacheManager(backend=RedisBackend())
lock = DistributedLock(cache, "critical_resource", timeout=30)

with lock:
    # Only one instance can execute this block at a time
    value = cache.get("counter") or 0
    cache.set("counter", value + 1)

📚 Documentation

Topics

🏗️ Architecture

┌──────────────────────────────────────┐
│      Unified API (CacheManager)      │
│  @cached | async with cache.lock()  │
└──────────┬───────────┬───────────────┘
           │           │
    ┌──────▼─────┐ ┌──▼────┐ ┌────────┐
    │   Memory   │ │ File  │ │ Redis  │
    │  Backend   │ │Backend│ │Backend │
    │            │ │       │ │        │
    │ - Dict     │ │SQLite │ │redis-py│
    │ - LRU      │ │+Memory│ │+hiredis│
    │ - TTL      │ │Hot    │ │Cluster │
    └────────────┘ │Reload │ └────────┘
                   └───────┘

🔬 Performance

Backend Read (P99) Write (P99) Throughput Hot Reload (100k)
Memory < 0.01ms < 0.01ms 200k ops/s N/A
File < 0.1ms < 1ms 50k ops/s < 5s
Redis < 1ms < 2ms 100k ops/s N/A

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🔗 Links

🌟 Star History

Star History Chart


Made with ❤️ by the Symphra Team

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

symphra_cache-0.1.0.tar.gz (124.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

symphra_cache-0.1.0-py3-none-any.whl (67.2 kB view details)

Uploaded Python 3

File details

Details for the file symphra_cache-0.1.0.tar.gz.

File metadata

  • Download URL: symphra_cache-0.1.0.tar.gz
  • Upload date:
  • Size: 124.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.5

File hashes

Hashes for symphra_cache-0.1.0.tar.gz
Algorithm Hash digest
SHA256 4aa163f4809edc539968d8dcee17921731fa84b13815da3ee206d98adb2ad88f
MD5 5fffa5e08cb07557517ed3dd79d3cc75
BLAKE2b-256 2e431b6e029200d958a8130bc2db743b1817c67adda5fe534eff2db9b53194bb

See more details on using hashes here.

File details

Details for the file symphra_cache-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for symphra_cache-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 29d0ffea2b08a901e4db5a67ea4a950dbb4d63453efb9e236493655dbe8bceb9
MD5 d2d57afdc35e1cd0528e43879fb0e841
BLAKE2b-256 f125a347df6a6b14027f51ab00f78196be23a6e14964b8e43a7a0ed47f6d68ba

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page