Based on the freecache library and the 'leasing' mechanism of the paper Scaling Memcache at Facebook.
cacheSize := 100 * 1024 * 1024 // 100MB
cache := memtable.New(cacheSize)
for {
key := []byte("some-key")
result := cache.Get(key)
if result.Status == memtable.GetStatusLeaseRejected {
time.Sleep(100 * time.Millisecond)
continue
}
if result.Status == memtable.GetStatusFound {
// cache hit
fmt.Println("Got value:", result.Value)
return
}
// cache miss but lease is granted
// get data from database
value := []byte("some-value")
affected := cache.Set(key, result.LeaseID, value)
fmt.Println("Affected:", affected)
return
}
The MIT License