Ralph::Query::QueryCache
Thread-safe query result cache with TTL and LRU eviction
This cache stores query results and provides:
- Time-to-live (TTL) for automatic expiration
- LRU (Least Recently Used) eviction when max size is reached
- Thread-safe access via mutex
- Table-based invalidation for write operations
- Cache statistics for monitoring
Example
cache = Ralph::Query::QueryCache.new(max_size: 1000, default_ttl: 5.minutes)
# Store a result
cache.set("query_key", results)
# Retrieve a result (returns nil if expired or not found)
if result = cache.get("query_key")
# Use cached result
end
# Invalidate all entries for a table
cache.invalidate_table("users")
# Get cache statistics
stats = cache.stats
puts "Hits: #{stats[:hits]}, Misses: #{stats[:misses]}"
Constructors
Create a new query cache
Parameters
max_size: Maximum number of entries before LRU eviction (default: 1000)default_ttl: Default time-to-live for entries (default: 5 minutes)enabled: Whether caching is enabled (default: true)
Instance methods
Get a cached result by key
Returns nil if not found, expired, or cache is disabled. Automatically removes expired entries.
Invalidate all cache entries that reference a specific table
This should be called after INSERT, UPDATE, or DELETE operations to ensure cached results don't return stale data.
prune_expired
Prune expired entries
This can be called periodically to clean up expired entries that haven't been accessed. Returns the number of entries removed.
Store a result in the cache
If the cache is at max capacity, evicts the least recently used entry.