Golang function calls result cache made easy.
To use this utility on your project, get it by running the following command:
go get github.com/josemiguelmelo/gocacheable
Currently, the providers available are:
-
BigCache (https://github.com/allegro/bigcache)
-
Redis (https://redis.io/)
For more information about providers, click here
Using cacheable is quite simple:
First of all, you must create a Cacheable Manager. This can be done by calling a single method:
managerIdentifier := "manager_id"
cacheableManager := gocacheable.NewCacheableManager(managerIdentifier)
A module is a feature related group, with a cache provider associated. In order to use gocacheable it is required to have at least one module.
To add a new module, you only need to add the following line to the code:
storageProvider := &bcProvider.BigCacheProvider{}
err := cacheableManager.AddModule(moduleName, storageProvider)
After having the cacheable manager and a module, to cache a function return you just need to call it inside Cacheable method.
Suppose you want to cache the function: func example() string
var outValue string
cacheKey := "test_object"
timeToLive := 2 * time.Second
err := cacheableManager.Cacheable(
moduleName,
cacheKey,
func() (interface{}, error) {
return example(), nil
},
&outValue,
timeToLive
)
When using the code above, if the call is already cached, it returns the cached value. Otherwise, it call the function, caches the result and returns the result into &outValue.