Initialize and use FreeCache
masterTo use FreeCache, initialize a new cache instance using freecache.NewCache(cacheSize) where cacheSize is the total memory allocated in bytes.
Key operations include:
Set(key, val, expire): Stores a byte slice value with a specified expiration time in seconds.Get(key): Retrieves the value associated with the key. Returns the value and an error if the key is not found.Del(key): Deletes a key. Returns the number of affected entries.EntryCount(): Returns the current number of entries in the cache.
Note on Expiration: If you set an expiration of X seconds, the actual duration will be within (X-1, X] seconds because sub-second precision is ignored during expiration calculation.
// In bytes, where 1024 * 1024 represents a single Megabyte, and 100 * 1024*1024 represents 100 Megabytes.
cacheSize := 100 * 1024 * 1024
cache := freecache.NewCache(cacheSize)
// Adjust GC frequency if allocating large amounts of memory
debug.SetGCPercent(20)
key := []byte("abc")
val := []byte("def")
expire := 60 // expire in 60 seconds
// Set a value
cache.Set(key, val, expire)
// Get a value
got, err := cache.Get(key)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s\n", got)
}
// Delete a value
affected := cache.Del(key)
fmt.Println("deleted key ", affected)
fmt.Println("entry count ", cache.EntryCount())