High-performance, thread-safe caching library for Go with automatic function wrapping and TTL support.
go get github.com/vnykmshr/obcache-gopackage main
import (
"fmt"
"time"
"github.com/vnykmshr/obcache-go/pkg/obcache"
)
func expensiveFunction(id int) (string, error) {
time.Sleep(100 * time.Millisecond) // Simulate expensive work
return fmt.Sprintf("result-%d", id), nil
}
func main() {
cache, _ := obcache.New(obcache.NewDefaultConfig())
// Wrap function with caching
cachedFunc := obcache.Wrap(cache, expensiveFunction)
// First call: slow (cache miss)
result1, _ := cachedFunc(123)
// Second call: fast (cache hit)
result2, _ := cachedFunc(123)
fmt.Println(result1, result2) // Same result, much faster
}cache, _ := obcache.New(obcache.NewDefaultConfig())
// Set with TTL
cache.Set("key", "value", time.Hour)
// Get value
if value, found := cache.Get("key"); found {
fmt.Println("Found:", value)
}
// Delete
cache.Delete("key")
// Stats
stats := cache.Stats()
fmt.Printf("Hit rate: %.1f%%\n", stats.HitRate())config := obcache.NewDefaultConfig().
WithMaxEntries(1000).
WithDefaultTTL(30 * time.Minute)
cache, _ := obcache.New(config)config := obcache.NewRedisConfig("localhost:6379").
WithDefaultTTL(time.Hour)
// Customize Redis key prefix
config.Redis.KeyPrefix = "myapp:"
cache, _ := obcache.New(config)import "github.com/vnykmshr/obcache-go/internal/eviction"
// LRU (Least Recently Used) - Default
config := obcache.NewDefaultConfig().
WithMaxEntries(1000).
WithEvictionType(eviction.LRU)
// LFU (Least Frequently Used)
config := obcache.NewDefaultConfig().
WithMaxEntries(1000).
WithEvictionType(eviction.LFU)
// FIFO (First In, First Out)
config := obcache.NewDefaultConfig().
WithMaxEntries(1000).
WithEvictionType(eviction.FIFO)config := obcache.NewDefaultConfig().
WithCompression(&compression.Config{
Enabled: true,
Algorithm: compression.CompressorGzip,
MinSize: 1000, // Only compress values > 1KB
})- Function wrapping - Automatically cache expensive function calls
- TTL support - Time-based expiration
- Multiple eviction strategies - LRU, LFU, and FIFO support
- Thread safe - Concurrent access support
- Redis backend - Distributed caching
- Compression - Automatic value compression (gzip/deflate)
- Prometheus metrics - Built-in metrics exporter
- Statistics - Hit rates, miss counts, etc.
- Context-aware hooks - Event callbacks for cache operations
See examples/ for complete examples:
MIT License - see LICENSE file.