Lựa chọn đúng định dạng serialization là chìa khóa để tăng tốc độ cache, giảm độ trễ và tiết kiệm tài nguyên vận hành.
Định dạng | Ưu điểm | Nhược điểm |
---|---|---|
JSON | Dễ đọc, tương thích đa ngôn ngữ | Chậm, kích thước lớn |
orjson | Tốc độ nhanh gấp 3-10 lần JSON, nhỏ gọn | Phụ thuộc vào thư viện bên ngoài |
Pickle | Tương thích phức tạp Python, kích thước nhỏ | Chỉ dùng trong môi trường Python, không an toàn khi dùng với dữ liệu không đáng tin |
SerializationManager
để kiểm soát serialize/deserialize với các định dạng trên, đồng thời theo dõi thời gian thực hiện và kích thước dữ liệu.APICacheManager
cho phép thiết lập định dạng mặc định và truyền tham số format khi lưu dữ liệu.class APICacheManager: def __init__(self, default_format: SerializationFormat = SerializationFormat.JSON): self.default_format = default_format self.serialization_manager = SerializationManager()
async def set(self, key: str, value: Any, ttl: int = 3600, format: SerializationFormat = None) -> bool: fmt = format or self.default_format if fmt == SerializationFormat.ORJSON: serialized_data, _ = self.serialization_manager.serialize_orjson(value) elif fmt == SerializationFormat.PICKLE: serialized_data, _ = self.serialization_manager.serialize_pickle(value) else: serialized_data, _ = self.serialization_manager.serialize_json(value) # Lưu dữ liệu vào cache (Redis, Memcached,...) return await self._store_in_cache(key, serialized_data, ttl)
Kích thước | Định dạng | Serialize (s) | Deserialize (s) | Kích thước lưu trữ (bytes) |
---|---|---|---|---|
Nhỏ (242 bytes) | orjson | 0.000000 | 0.000001 | 221 |
| JSON | 0.000003 | 0.000002 | 242 |
| Pickle | 0.000001 | 0.000001 | 232 |
Trung bình (561 bytes) | orjson | 0.000001 | 0.000001 | 516 |
| JSON | 0.000005 | 0.000004 | 561 |
| Pickle | 0.000002 | 0.000002 | 521 |
Lớn (3346 bytes) | orjson | 0.000003 | 0.000006 | 2963 |
| JSON | 0.000030 | 0.000022 | 3346 |
| Pickle | 0.000009 | 0.000009 | 2536 |
cache_mgr_fast = APICacheManager(default_format=SerializationFormat.ORJSON)cache_mgr_compatible = APICacheManager(default_format=SerializationFormat.JSON)
async def robust_cache_get(key: str, formats: List[SerializationFormat]): for fmt in formats: try: data = await cache_mgr.get(key, format=fmt) if data: return data except Exception: continue return None