2023-04-06 08:57:14 +00:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/gomodule/redigo/redis"
|
2023-04-06 10:41:54 +00:00
|
|
|
"qoobing.com/gomod/log"
|
2023-04-06 08:57:14 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2023-04-10 03:47:31 +00:00
|
|
|
ErrNotFound = errors.New("not found")
|
|
|
|
OptWithoutGetter = optWithoutGetter{} // for get only
|
|
|
|
OptWithCreateTime = optWithCreateTime{} // for set & get
|
2023-04-06 08:57:14 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Cacher[T any] interface {
|
2023-04-10 03:47:31 +00:00
|
|
|
GetFromCache(id string, options ...Option) (dat *T, err error)
|
|
|
|
SetIntoCache(id string, dat *T, options ...Option) (err error)
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type Getter[T any] interface {
|
|
|
|
GetById(id string) (dat *T, err error)
|
|
|
|
}
|
|
|
|
|
2023-04-10 03:47:31 +00:00
|
|
|
type (
|
|
|
|
Option any
|
|
|
|
optWithoutGetter struct{} // for get only
|
|
|
|
optWithCreateTime struct{ createtime *time.Time } // for set & get
|
|
|
|
Options struct {
|
|
|
|
withoutGetter *optWithoutGetter
|
|
|
|
withCreateTime *optWithCreateTime
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
func optionParser(options ...Option) (opts Options, err error) {
|
|
|
|
var l = len(options)
|
|
|
|
if l == 0 {
|
|
|
|
return opts, nil
|
|
|
|
}
|
|
|
|
//TODO: add i out of range & options[i] type mismatch panic recover
|
|
|
|
for i := 0; i < l; i++ {
|
|
|
|
o := options[i]
|
|
|
|
switch o.(type) {
|
|
|
|
case optWithoutGetter:
|
|
|
|
opts.withoutGetter = new(optWithoutGetter)
|
|
|
|
case optWithCreateTime:
|
|
|
|
opts.withCreateTime = new(optWithCreateTime)
|
|
|
|
i++
|
|
|
|
opts.withCreateTime.createtime = options[i].(*time.Time)
|
|
|
|
default:
|
|
|
|
panic("unreachable code, maybe miss some code modification")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return opts, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func isOptWithCreateTimeForSetter(opts Options) bool {
|
|
|
|
if opts.withCreateTime == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
var createtime = opts.withCreateTime.createtime
|
|
|
|
if createtime == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return !createtime.IsZero()
|
|
|
|
}
|
|
|
|
|
|
|
|
func isOptWithCreateTimeForGetter(opts Options) bool {
|
|
|
|
if opts.withCreateTime == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
var createtime = opts.withCreateTime.createtime
|
|
|
|
if createtime == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return createtime.IsZero()
|
|
|
|
}
|
|
|
|
|
2023-04-06 08:57:14 +00:00
|
|
|
type Config struct {
|
2023-04-10 03:47:31 +00:00
|
|
|
UseLocalCache bool // use localcache or not
|
|
|
|
LocalCacheLifetimeSecond int64 // local cache lifetime(t<0: forever; t=0: default; t>0: seconds)
|
|
|
|
UseRedisCache bool // use redis or not
|
|
|
|
RedisCacheConn redis.Conn // redis.Conn
|
|
|
|
RedisCacheKeyPrefix string // redis key prefix
|
|
|
|
RedisCacheLifetimeSecond int64 // redis cache lifetime(t<0: forever; t=0: default; t>0: seconds)
|
|
|
|
UseGetter bool // not used
|
|
|
|
GetterNoWarning bool // no warning if no getter
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewCache[T any](getter Getter[T], cfg Config) Cacher[T] {
|
|
|
|
var c = new(cacher[T])
|
|
|
|
// Getter
|
2023-04-10 03:47:31 +00:00
|
|
|
c.cfg = cfg
|
2023-04-06 08:57:14 +00:00
|
|
|
c.getter = getter
|
|
|
|
|
|
|
|
// Local cache
|
|
|
|
if cfg.UseLocalCache {
|
|
|
|
c.localCache = new(localCacher[T])
|
|
|
|
c.localCache.cacheItems = map[string]*cacheItem[T]{}
|
2023-04-10 03:47:31 +00:00
|
|
|
c.localCache.cacheDuration = time.Duration(cfg.LocalCacheLifetimeSecond) * time.Second
|
|
|
|
if c.localCache.cacheDuration.Nanoseconds() == 0 {
|
|
|
|
c.localCache.cacheDuration = 60 * time.Second
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Redis cache
|
|
|
|
if cfg.UseRedisCache && cfg.RedisCacheConn != nil {
|
2023-04-06 10:41:54 +00:00
|
|
|
if cfg.RedisCacheKeyPrefix == "" {
|
|
|
|
panic("redis cache's key prefix must not be null")
|
|
|
|
}
|
2023-04-10 03:47:31 +00:00
|
|
|
c.redisCache = new(redisCacher[T])
|
|
|
|
c.redisCache.rds = cfg.RedisCacheConn
|
|
|
|
c.redisCache.cacheDuration = time.Duration(cfg.RedisCacheLifetimeSecond) * time.Second
|
2023-04-06 10:41:54 +00:00
|
|
|
c.redisCache.cachePrefix = fmt.Sprintf("%s-cache-id:", cfg.RedisCacheKeyPrefix)
|
2023-04-10 03:47:31 +00:00
|
|
|
if c.redisCache.cacheDuration.Nanoseconds() == 0 {
|
|
|
|
c.redisCache.cacheDuration = 180 * time.Second
|
|
|
|
}
|
2023-04-06 08:57:14 +00:00
|
|
|
} else if cfg.UseRedisCache {
|
|
|
|
panic("want to user redis cache, but redis.Conn is nil")
|
|
|
|
}
|
|
|
|
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
|
|
|
type cacheItem[T any] struct {
|
2023-04-06 10:41:54 +00:00
|
|
|
Data *T `json:"d"` //cache data
|
|
|
|
CreateTime time.Time `json:"t"` //cache create time
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type localCacher[T any] struct {
|
2023-04-10 03:47:31 +00:00
|
|
|
cacheItems map[string]*cacheItem[T]
|
|
|
|
cacheDuration time.Duration
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
|
2023-04-06 10:41:54 +00:00
|
|
|
type redisCacher[T any] struct {
|
2023-04-10 03:47:31 +00:00
|
|
|
rds redis.Conn
|
|
|
|
cachePrefix string
|
|
|
|
cacheDuration time.Duration
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type cacher[T any] struct {
|
2023-04-10 03:47:31 +00:00
|
|
|
cfg Config
|
2023-04-06 08:57:14 +00:00
|
|
|
getter Getter[T]
|
|
|
|
localCache *localCacher[T]
|
|
|
|
redisCache *redisCacher[T]
|
|
|
|
}
|
|
|
|
|
2023-04-10 03:47:31 +00:00
|
|
|
func (c *localCacher[T]) GetFromCache(id string, options ...Option) (t *T, err error) {
|
|
|
|
var a, ok = c.cacheItems[id]
|
|
|
|
if !ok {
|
2023-04-06 10:41:54 +00:00
|
|
|
return nil, ErrNotFound
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
2023-04-10 03:47:31 +00:00
|
|
|
|
|
|
|
if c.cacheDuration.Nanoseconds() > 0 {
|
|
|
|
var earliestCreateTime = time.Now().Add(-c.cacheDuration)
|
|
|
|
if a.CreateTime.Before(earliestCreateTime) {
|
|
|
|
log.Infof("app(%s) is in redis cache but expired", id)
|
|
|
|
//TODO: cocurrent
|
|
|
|
delete(c.cacheItems, id)
|
|
|
|
return nil, ErrNotFound
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
opt, err := optionParser(options...)
|
|
|
|
if err == nil && isOptWithCreateTimeForGetter(opt) {
|
|
|
|
*opt.withCreateTime.createtime = a.CreateTime
|
|
|
|
}
|
|
|
|
|
|
|
|
return a.Data, nil
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
|
2023-04-10 03:47:31 +00:00
|
|
|
func (c *localCacher[T]) SetIntoCache(id string, t *T, options ...Option) (err error) {
|
|
|
|
var newitem = &cacheItem[T]{Data: t}
|
|
|
|
opt, err := optionParser(options...)
|
|
|
|
if err == nil && isOptWithCreateTimeForSetter(opt) {
|
|
|
|
newitem.CreateTime = *opt.withCreateTime.createtime
|
|
|
|
} else {
|
|
|
|
newitem.CreateTime = time.Now()
|
2023-04-06 10:41:54 +00:00
|
|
|
}
|
2023-04-10 03:47:31 +00:00
|
|
|
c.cacheItems[id] = newitem
|
2023-04-06 08:57:14 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-04-10 03:47:31 +00:00
|
|
|
func (c *redisCacher[T]) GetFromCache(id string, options ...Option) (*T, error) {
|
2023-04-06 08:57:14 +00:00
|
|
|
var (
|
|
|
|
rds = c.rds
|
2023-04-06 10:41:54 +00:00
|
|
|
redisKey = c.cachePrefix + id
|
2023-04-06 08:57:14 +00:00
|
|
|
redisValue = ""
|
|
|
|
err error = nil
|
|
|
|
)
|
|
|
|
|
|
|
|
// Step 1. read from redis
|
|
|
|
if redisValue, err = redis.String(rds.Do("GET", redisKey)); err != nil {
|
2023-04-06 10:41:54 +00:00
|
|
|
log.Infof("get cache failed: 'redis return<%s>'", err.Error())
|
|
|
|
return nil, ErrNotFound
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Step 2. decode from string
|
2023-04-06 10:41:54 +00:00
|
|
|
a := &cacheItem[T]{}
|
2023-04-06 08:57:14 +00:00
|
|
|
if err = json.Unmarshal([]byte(redisValue), a); err != nil {
|
2023-04-06 10:41:54 +00:00
|
|
|
log.Errorf("get cache failed: 'json unmarshal failed <%s>'", err.Error())
|
|
|
|
return nil, ErrNotFound
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Step 3. check expire time
|
2023-04-10 03:47:31 +00:00
|
|
|
if c.cacheDuration.Nanoseconds() > 0 {
|
|
|
|
var earliestCreateTime = time.Now().Add(-c.cacheDuration)
|
2023-04-06 08:57:14 +00:00
|
|
|
if a.CreateTime.Before(earliestCreateTime) {
|
2023-04-06 10:41:54 +00:00
|
|
|
log.Infof("app(%s) is in redis cache but expired", id)
|
|
|
|
return nil, ErrNotFound
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-10 03:47:31 +00:00
|
|
|
// Step 4. get cache creattime if need
|
|
|
|
opt, err := optionParser(options...)
|
|
|
|
if err == nil && isOptWithCreateTimeForGetter(opt) {
|
|
|
|
*opt.withCreateTime.createtime = a.CreateTime
|
|
|
|
}
|
|
|
|
|
2023-04-06 10:41:54 +00:00
|
|
|
return a.Data, nil
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
|
2023-04-10 03:47:31 +00:00
|
|
|
func (c *redisCacher[T]) SetIntoCache(id string, t *T, options ...Option) error {
|
2023-04-06 08:57:14 +00:00
|
|
|
var (
|
2023-04-10 03:47:31 +00:00
|
|
|
opt, _ = optionParser(options...)
|
2023-04-06 08:57:14 +00:00
|
|
|
rds = c.rds
|
2023-04-06 10:41:54 +00:00
|
|
|
redisKey = c.cachePrefix + id
|
2023-04-06 08:57:14 +00:00
|
|
|
redisValue = []byte{}
|
|
|
|
err error = nil
|
|
|
|
)
|
|
|
|
|
2023-04-10 03:47:31 +00:00
|
|
|
// Step 1. encode to string
|
|
|
|
var a = cacheItem[T]{Data: t}
|
|
|
|
if err == nil && isOptWithCreateTimeForSetter(opt) {
|
|
|
|
a.CreateTime = *opt.withCreateTime.createtime
|
|
|
|
} else {
|
|
|
|
a.CreateTime = time.Now()
|
|
|
|
}
|
2023-04-06 08:57:14 +00:00
|
|
|
if redisValue, err = json.Marshal(a); err != nil {
|
2023-04-06 10:41:54 +00:00
|
|
|
log.Errorf("set cache failed: 'json marshal failed <%s>'", err.Error())
|
|
|
|
return errors.New("set cache failed: 'marshal failed'")
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
|
2023-04-10 03:47:31 +00:00
|
|
|
// Step 2. write into redis
|
2023-04-06 08:57:14 +00:00
|
|
|
if _, err = rds.Do("SET", redisKey, string(redisValue)); err != nil {
|
2023-04-06 10:41:54 +00:00
|
|
|
log.Errorf("set cache failed: 'redis failed <%s>'", err.Error())
|
|
|
|
return errors.New("set cache failed: 'redis failed'")
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-04-10 03:47:31 +00:00
|
|
|
func (c *cacher[T]) GetFromCache(id string, options ...Option) (dat *T, err error) {
|
2023-04-06 08:57:14 +00:00
|
|
|
// Step 1. check id
|
2023-04-10 03:47:31 +00:00
|
|
|
if len(id) < 1 {
|
2023-04-06 08:57:14 +00:00
|
|
|
return nil, ErrNotFound
|
|
|
|
}
|
|
|
|
|
2023-04-10 03:47:31 +00:00
|
|
|
var opt, _ = optionParser(options...)
|
2023-04-06 08:57:14 +00:00
|
|
|
// Step 2. get from [local]
|
|
|
|
if c.localCache != nil {
|
2023-04-10 03:47:31 +00:00
|
|
|
if dat, err := c.localCache.GetFromCache(id, options...); err == nil {
|
2023-04-06 08:57:14 +00:00
|
|
|
log.Infof("get cache(id:%s) from localCacher success", id)
|
|
|
|
return dat, nil
|
|
|
|
}
|
2023-04-10 03:47:31 +00:00
|
|
|
log.Infof("get cache(id:%s) from localCacher failed, try next", id)
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Step 3. get from [redis]
|
|
|
|
if c.redisCache != nil {
|
2023-04-10 03:47:31 +00:00
|
|
|
if opt.withCreateTime == nil { //get create time from redis
|
|
|
|
options = append(options, OptWithCreateTime, new(time.Time))
|
|
|
|
}
|
|
|
|
if dat, err := c.redisCache.GetFromCache(id, options...); err == nil {
|
2023-04-06 10:41:54 +00:00
|
|
|
if c.localCache != nil {
|
2023-04-10 03:47:31 +00:00
|
|
|
c.localCache.SetIntoCache(id, dat, options...) //set create time from redis
|
|
|
|
log.Infof("set cache(id:%s) to localCache by redisCacher done", id)
|
2023-04-06 10:41:54 +00:00
|
|
|
}
|
2023-04-06 08:57:14 +00:00
|
|
|
log.Infof("get cache(id:%s) from redisCacher success", id)
|
|
|
|
return dat, nil
|
|
|
|
}
|
2023-04-10 03:47:31 +00:00
|
|
|
log.Infof("get cache(id:%s) from redisCacher failed, try next", id)
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
2023-04-10 03:47:31 +00:00
|
|
|
|
|
|
|
var getter = c.getter
|
|
|
|
if opt.withoutGetter != nil {
|
|
|
|
log.Infof("all cache failed, and option 'withnogetter' is set, return ErrNotFound")
|
|
|
|
return nil, ErrNotFound
|
|
|
|
}
|
|
|
|
if getter == nil {
|
|
|
|
log.Infof("all cache failed, and getter is nil, return ErrNotFound")
|
|
|
|
if c.cfg.GetterNoWarning == false {
|
|
|
|
log.Warningf("cache 'getter' is nil, did you save right config in database?")
|
|
|
|
}
|
2023-04-06 10:41:54 +00:00
|
|
|
return nil, ErrNotFound
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Step 4. get from [storager(database or somewhere)]
|
2023-04-10 03:47:31 +00:00
|
|
|
dat, err = getter.GetById(id)
|
2023-04-06 08:57:14 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Errorf("cache(id:%s) is not in database, something error: %s", id, err)
|
2023-04-06 10:41:54 +00:00
|
|
|
return nil, ErrNotFound
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
log.Infof("get cache(id:%s) from exportStorager(maybe database) success", id)
|
|
|
|
|
|
|
|
// Step 5. set to cacha
|
|
|
|
if c.localCache != nil {
|
2023-04-10 03:47:31 +00:00
|
|
|
c.localCache.SetIntoCache(id, dat, options...)
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
if c.redisCache != nil {
|
2023-04-10 03:47:31 +00:00
|
|
|
c.redisCache.SetIntoCache(id, dat, options...)
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Step 6. return
|
|
|
|
log.PrintPretty("success cached/return app:", dat)
|
|
|
|
return dat, nil
|
|
|
|
}
|
|
|
|
|
2023-04-10 03:47:31 +00:00
|
|
|
func (c *cacher[T]) SetIntoCache(id string, dat *T, options ...Option) (err error) {
|
2023-04-06 08:57:14 +00:00
|
|
|
// localCache
|
|
|
|
if c.localCache != nil {
|
2023-04-10 03:47:31 +00:00
|
|
|
if err = c.localCache.SetIntoCache(id, dat, options...); err != nil {
|
2023-04-06 08:57:14 +00:00
|
|
|
log.Infof("set data into localCache failed, err:%s", err)
|
2023-04-06 10:41:54 +00:00
|
|
|
} else {
|
|
|
|
log.Debugf("success set data into localCache, id: %s", id)
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// redisCache
|
|
|
|
if c.redisCache != nil {
|
2023-04-10 03:47:31 +00:00
|
|
|
if err = c.redisCache.SetIntoCache(id, dat, options...); err != nil {
|
2023-04-06 08:57:14 +00:00
|
|
|
log.Infof("set data into redisCache failed, err:%s", err)
|
2023-04-06 10:41:54 +00:00
|
|
|
} else {
|
|
|
|
log.Debugf("success set data into redisCache, id: %s", id)
|
2023-04-06 08:57:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|