MemCache is a simple in-memory cache implementation written in Go. It provides basic caching functionalities such as storing, retrieving, and deleting key-value pairs with optional time-to-live (TTL) support and eviction policies.
- In-Memory Storage: Data is stored in memory, providing fast read and write access.
- Key-Value Storage: Data is stored as key-value pairs, allowing efficient retrieval based on keys.
- Time-to-Live (TTL): Supports setting a TTL for cache entries, after which they are automatically removed.
- Eviction Policies: Supports eviction policies to manage cache size when reaching capacity.
- Concurrency-Safe: Designed to support concurrent read and write operations safely.
To create a new MemCache instance, use the NewCache function along with optional configuration options:
cache := NewCache(WithTTL(10*time.Second), WithEvictionPolicy("Oldest"))Insert key-value pairs into the cache using the Set method:
err := cache.Set("bucket", "key", []byte("value"))
if err != nil {
// Handle error
}To retrieve a value from the cache, use the Get method:
value, err := cache.Get("bucket", "key")
if err != nil {
// Handle error
}Delete an entry from the cache using the Delete method:
err := cache.Delete("bucket", "key")
if err != nil {
// Handle error
}MemCache supports configuration options such as TTL and eviction policy. You can apply these options during cache creation or update them later:
// Apply options during cache creation
cache := NewCache(WithTTL(10*time.Second), WithEvictionPolicy("Oldest"))
// Update options later
cache.ApplyOptions(WithTTL(20*time.Second))Available Eviction Policy: Determines how Memcached handles cache capacity limitations. The WithEvictionPolicy option accepts a string argument specifying the desired policy:
- "Oldest" (default): Evicts the oldest item.