import asyncio
from ri import (
RiCacheModule,
RiCacheConfig,
RiCacheManager,
RiCacheBackendType,
RiCachePolicy,
RiCacheStats,
RiCachedValue,
RiCacheEvent,
)
async def main():
config = RiCacheConfig()
config.backend_type = RiCacheBackendType.Memory
config.default_ttl_secs = 300
config.max_memory_mb = 512
cache_module = RiCacheModule(config)
manager = RiCacheManager()
policy = RiCachePolicy()
policy.ttl_seconds = 600
policy.max_size = 1000
policy.eviction_policy = "lru"
print("Setting cache values...")
string_value = RiCachedValue()
string_value.data = b"Hello, Ri Cache!"
string_value.content_type = "text/plain"
manager.set("greeting", string_value, policy)
json_value = RiCachedValue()
json_value.data = b'{"name": "John", "age": 30, "city": "New York"}'
json_value.content_type = "application/json"
manager.set("user:123", json_value, policy)
binary_value = RiCachedValue()
binary_value.data = b"\x00\x01\x02\x03\x04\x05"
binary_value.content_type = "application/octet-stream"
manager.set("binary:data", binary_value, policy)
print("\nGetting cache values...")
greeting = manager.get("greeting")
if greeting:
print(f"Greeting: {greeting.data.decode('utf-8')}")
user = manager.get("user:123")
if user:
print(f"User data: {user.data.decode('utf-8')}")
exists = manager.exists("greeting")
print(f"\nKey 'greeting' exists: {exists}")
print("\nCache Statistics:")
stats = RiCacheStats()
print(f"Cache hits: {stats.hits}")
print(f"Cache misses: {stats.misses}")
print(f"Hit rate: {stats.hit_rate:.2%}")
print(f"Total keys: {stats.total_keys}")
print(f"Memory usage: {stats.memory_usage_bytes} bytes")
print("\nDeleting key 'binary:data'...")
manager.delete("binary:data")
exists_after_delete = manager.exists("binary:data")
print(f"Key 'binary:data' exists after delete: {exists_after_delete}")
print("\nSetting value with custom TTL...")
temp_value = RiCachedValue()
temp_value.data = b"This will expire soon"
temp_value.content_type = "text/plain"
custom_policy = RiCachePolicy()
custom_policy.ttl_seconds = 10
manager.set("temp:key", temp_value, custom_policy)
print("Value set with 10 second TTL")
print("\nAll cache keys:")
keys = manager.keys()
for key in keys:
print(f" - {key}")
print("\nClearing cache...")
manager.clear()
print("Cache cleared!")
print("\nCache operations completed successfully!")
if __name__ == "__main__":
asyncio.run(main())