Use a Loader to lazily initialize cache items
v3The Loader interface allows you to define a function that is called when a requested key is missing from the cache. This is useful for loading data from external sources like files or HTTP requests. You can use ttlcache.LoaderFunc to create a loader from a simple function.
loader := ttlcache.LoaderFunc[K, V](func(c *ttlcache.Cache[K, V], key K) *ttlcache.Item[K, V] {
// logic to load data
return c.Set(key, value)
})
cache := ttlcache.New[K, V](ttlcache.WithLoader[K, V](loader))func main() {
loader := ttlcache.LoaderFunc[string, string](
func(c *ttlcache.Cache[string, string], key string) *ttlcache.Item[string, string] {
// load from file/make an HTTP request
item := c.Set("key from file", "value from file")
return item
})
cache := ttlcache.New[string, string](
ttlcache.WithLoader[string, string](loader),
)
item := cache.Get("key from file")
}