生产级 Python 异步缓存库,支持内存、文件(热重载)、Redis 后端
Project description
Symphra Cache
🚀 Production-grade async caching library for Python 3.11+
✨ 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
- Simple decorator API (
📦 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
- English Docs: https://symphra-cache.readthedocs.io/en/
- 中文文档: https://symphra-cache.readthedocs.io/zh/
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.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Links
- GitHub: https://github.com/getaix/symphra-cache
- PyPI: https://pypi.org/project/symphra-cache/
- Documentation: https://getaix.github.io/symphra-cache/
- Issues: https://github.com/getaix/symphra-cache/issues
- Changelog: CHANGELOG.md
🌟 Star History
Made with ❤️ by the Symphra Team
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4aa163f4809edc539968d8dcee17921731fa84b13815da3ee206d98adb2ad88f
|
|
| MD5 |
5fffa5e08cb07557517ed3dd79d3cc75
|
|
| BLAKE2b-256 |
2e431b6e029200d958a8130bc2db743b1817c67adda5fe534eff2db9b53194bb
|
File details
Details for the file symphra_cache-0.1.0-py3-none-any.whl.
File metadata
- Download URL: symphra_cache-0.1.0-py3-none-any.whl
- Upload date:
- Size: 67.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.9.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
29d0ffea2b08a901e4db5a67ea4a950dbb4d63453efb9e236493655dbe8bceb9
|
|
| MD5 |
d2d57afdc35e1cd0528e43879fb0e841
|
|
| BLAKE2b-256 |
f125a347df6a6b14027f51ab00f78196be23a6e14964b8e43a7a0ed47f6d68ba
|