Compare commits

..

No commits in common. "master" and "v1.3.1" have entirely different histories.

View File

@ -1,12 +1,10 @@
package cache
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"sync"
"time"
"github.com/gomodule/redigo/redis"
@ -16,7 +14,6 @@ import (
var (
ErrExpired = errors.New("expired")
ErrNotFound = errors.New("not found")
ErrTimeout = errors.New("not found(timeout)")
OptWithoutGetter = optWithoutGetter{} // for get only
OptWithCreateTime = optWithCreateTime{} // for set & get
OptWithRedisConn = optWithRedisConn{} // for set & get
@ -66,13 +63,14 @@ type Config struct {
func NewCache[T any](getter Getter[T], cfg Config) Cacher[T] {
var c = new(cacher[T])
// Getter
c.cfg = cfg
c.getter = getter
// Local cache
if cfg.UseLocalCache {
c.localCache = new(localCacher[T])
c.localCache.cacher = c
c.localCache.cacheItems = sync.Map{} //map[string]*cacheItem[T]{}
c.localCache.cacheItems = map[string]*cacheItem[T]{}
c.localCache.cacheDuration = time.Duration(cfg.LocalCacheLifetimeSecond) * time.Second
if c.localCache.cacheDuration.Nanoseconds() == 0 {
c.localCache.cacheDuration = 60 * time.Second
@ -102,7 +100,6 @@ func NewCache[T any](getter Getter[T], cfg Config) Cacher[T] {
cfg.UseExpiredCache = &[]bool{true}[0]
}
c.cfg = cfg
name := reflect.TypeOf(*new(T)).String()
log.PrintPretty("new cache '"+name+"' by config:", cfg)
return c
@ -162,9 +159,9 @@ type cacheItem[T any] struct {
}
type localCacher[T any] struct {
cacher *cacher[T] // parents cacher pointer
cacheItems sync.Map // map[string]*cacheItem[T]
cacheDuration time.Duration // cache alive duration
cacher *cacher[T]
cacheItems map[string]*cacheItem[T]
cacheDuration time.Duration
}
type redisCacher[T any] struct {
@ -177,11 +174,9 @@ type redisCacher[T any] struct {
func (c *localCacher[T]) GetFromCache(id string, options ...Option) (t *T, err error) {
// Step 1. get from map
var a *cacheItem[T] = nil
if aa, ok := c.cacheItems.Load(id); !ok {
var a, ok = c.cacheItems[id]
if !ok {
return nil, ErrNotFound
} else if a, ok = aa.(*cacheItem[T]); !ok {
panic("unreachable code, inner item type must be '*cacheItem[T]'")
}
// Step 2. check is expired or not
@ -194,7 +189,8 @@ func (c *localCacher[T]) GetFromCache(id string, options ...Option) (t *T, err e
err = ErrExpired
} else {
log.Infof("cache(%s) is in local cache but expired, we delete it", id)
c.cacheItems.Delete(id)
//TODO: cocurrent
delete(c.cacheItems, id)
return nil, ErrNotFound
}
}
@ -210,7 +206,7 @@ func (c *localCacher[T]) GetFromCache(id string, options ...Option) (t *T, err e
if err == ErrExpired {
return a.Data, ErrExpired
} else if err != nil {
panic("unreachable code: only ErrExpired error valid when data exist")
panic("unreachable code")
}
return a.Data, nil
}
@ -223,7 +219,7 @@ func (c *localCacher[T]) SetIntoCache(id string, t *T, options ...Option) (err e
} else {
newitem.CreateTime = time.Now()
}
c.cacheItems.Store(id, newitem)
c.cacheItems[id] = newitem
return nil
}
@ -238,14 +234,7 @@ func (c *redisCacher[T]) GetFromCache(id string, options ...Option) (*T, error)
if opt.withRedisConn != nil && opt.withRedisConn.redisconn != nil {
rds = opt.withRedisConn.redisconn
} else if c.rdsPool != nil {
// timeout context
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// redis conn from pool
rds, err = c.rdsPool.GetContext(ctx)
if err != nil {
return nil, ErrTimeout
}
rds = c.rdsPool.Get()
defer rds.Close()
} else if c.rds != nil {
rds = c.rds
@ -305,14 +294,7 @@ func (c *redisCacher[T]) SetIntoCache(id string, t *T, options ...Option) error
if opt.withRedisConn != nil && opt.withRedisConn.redisconn != nil {
rds = opt.withRedisConn.redisconn
} else if c.rdsPool != nil {
// timeout context
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// redis conn from pool
rds, err = c.rdsPool.GetContext(ctx)
if err != nil {
return errors.New("set cache failed: 'get redis conn timeout'")
}
rds = c.rdsPool.Get()
defer rds.Close()
} else if c.rds != nil {
rds = c.rds
@ -380,7 +362,7 @@ func (c *cacher[T]) GetFromCache(id string, options ...Option) (dat *T, err erro
log.Infof("get cache(id:%s) from redisCacher success(but expired), need try next", id)
lastExpiredDat = dat
} else {
log.Infof("get cache(id:%s) from redisCacher failed, need try from next cacher", id)
log.Infof("get cache(id:%s) from redisCacher failed, need try next", id)
}
}