package cache import ( "context" "git.nspix.com/golang/kos/util/env" "github.com/patrickmn/go-cache" "os" "time" ) var ( memCacheDefaultExpired time.Duration memCacheCleanupInterval time.Duration ) func init() { memCacheDefaultExpired, _ = time.ParseDuration(env.Get("MEMCACHE_DEFAULT_EXPIRED", "1h")) memCacheCleanupInterval, _ = time.ParseDuration(env.Get("MEMCACHE_CLEANUP_INTERVAL", "10m")) if memCacheDefaultExpired < time.Second*5 { memCacheDefaultExpired = time.Second * 5 } if memCacheCleanupInterval < time.Minute { memCacheCleanupInterval = time.Minute } } type MemCache struct { engine *cache.Cache } func (cache *MemCache) Try(ctx context.Context, key string, cb LoadFunc) (buf []byte, err error) { var ( ok bool ) if buf, ok = cache.Get(ctx, key); ok { return buf, nil } if cb == nil { return nil, os.ErrNotExist } if buf, err = cb(ctx); err == nil { cache.Set(ctx, key, buf) } return } func (cache *MemCache) Set(ctx context.Context, key string, buf []byte) { cache.engine.Set(key, buf, 0) } func (cache *MemCache) SetEx(ctx context.Context, key string, buf []byte, expire time.Duration) { cache.engine.Set(key, buf, expire) } func (cache *MemCache) Get(ctx context.Context, key string) (buf []byte, ok bool) { var ( val any ) if val, ok = cache.engine.Get(key); ok { buf, ok = val.([]byte) } return } func (cache *MemCache) Del(ctx context.Context, key string) { cache.engine.Delete(key) } func NewMemCache() *MemCache { return &MemCache{ engine: cache.New(memCacheDefaultExpired, memCacheCleanupInterval), } }