Install github.com/pangpanglabs/goutils/cache
package.
go get -u github.com/pangpanglabs/goutils/cache
Use cache.Cache
interface type
var mycache cache.Cache
Create local cache(use sync.Map
as a cache storage):
mycache = cache.Local{ExpireTime: time.Hour * 24}
Create redis cache
redisConn := "redis://127.0.0.1:6379"
mycache = cache.NewRedis(redisConn)
- default expire time:
time.Hour * 24
- default
Converter
:JsonConverter
Or, create redis cache with addiotional options:
redisConn := "redis://127.0.0.1:6379"
mycache = cache.NewRedis(redisConn,
cache.WithExpireTime(time.Hour*3),
cache.WithGobConverter(),
func(redis *cache.Redis) {
// setup additional options
},
)
If you want to use
GobConverter
, you have to identify the concrete type of a value usinggob.Register()
function.
Save to cache:
loadFromCache, err := cache.LoadOrStore(key, &target,
func() (interface{}, error) {
// load and return value
})
Delete from cache:
cache.Delete(key)