Overview
simple_cache provides a generic in-memory cache with Least Recently Used (LRU) eviction policy for Eiffel applications. It supports optional Time-to-Live (TTL) for automatic entry expiration and tracks cache statistics like hits, misses, and evictions.
Quick Start
Installation
<library name="simple_cache" location="$SIMPLE_CACHE\simple_cache.ecf"/>
Basic Usage
local
cache: SIMPLE_CACHE [STRING]
do
-- Create cache with max 100 entries
create cache.make (100)
-- Store values
cache.put ("user:123", "Alice")
cache.put ("user:456", "Bob")
-- Retrieve values
if attached cache.get ("user:123") as name then
print ("Found: " + name)
end
-- Check statistics
print ("Hit rate: " + (cache.hit_rate * 100).out + "%%")
end
Features
Generic Storage
STRING keys with any value type via SIMPLE_CACHE [G]
LRU Eviction
Automatically removes least recently used entries when full
TTL Support
Optional time-to-live per entry or default expiration
Statistics
Track hits, misses, evictions, and hit rate
Redis Support
SIMPLE_REDIS_CACHE for distributed caching via Redis
Redis Client
SIMPLE_REDIS for low-level Redis commands
TTL (Time-to-Live)
-- Cache with default 1-hour TTL
create cache.make_with_ttl (100, 3600)
-- Store with custom TTL (5 minutes)
cache.put_with_ttl ("temp:xyz", data, 300)
-- Entries automatically expire
Redis Cache
local
cache: SIMPLE_REDIS_CACHE
do
create cache.make ("localhost", 6379, 1000)
if cache.connect then
cache.put ("user:123", user_json)
if attached cache.get ("user:123") as data then
print (data)
end
cache.disconnect
end
end
Redis Client
local
redis: SIMPLE_REDIS
do
create redis.make ("localhost", 6379)
if redis.connect then
redis.set ("key", "value")
redis.setex ("temp", 60, "expires in 1 min")
redis.incr ("counter")
if redis.ping then
print ("Connected!")
end
redis.disconnect
end
end
API Reference
make (a_max_size: INTEGER)
Create cache with maximum entries, no expiration.
Require
Ensure
make_with_ttl (a_max_size, a_ttl: INTEGER)
Create cache with maximum entries and default TTL in seconds.
put (a_key: STRING; a_value: G)
Store value with key. Uses default TTL if set.
get (a_key: STRING): detachable G
Retrieve value. Returns Void if not found or expired.
Statistics
| Feature | Type | Description |
|---|---|---|
hits | INTEGER | Cache hit count |
misses | INTEGER | Cache miss count |
evictions | INTEGER | LRU eviction count |
hit_rate | REAL_64 | Hit rate (0.0 to 1.0) |