|
@@ -2,14 +2,50 @@ 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) (value any, err error) {
|
|
|
+ var (
|
|
|
+ ok bool
|
|
|
+ )
|
|
|
+ if value, ok = cache.engine.Get(key); ok {
|
|
|
+ return value, nil
|
|
|
+ }
|
|
|
+ if cb == nil {
|
|
|
+ return nil, os.ErrNotExist
|
|
|
+ }
|
|
|
+ if value, err = cb(ctx); err == nil {
|
|
|
+ cache.engine.Set(key, value, 0)
|
|
|
+ }
|
|
|
+ return
|
|
|
+}
|
|
|
+
|
|
|
func (cache *MemCache) Set(ctx context.Context, key string, value any) {
|
|
|
cache.engine.Set(key, value, 0)
|
|
|
}
|
|
@@ -28,6 +64,6 @@ func (cache *MemCache) Del(ctx context.Context, key string) {
|
|
|
|
|
|
func NewMemCache() *MemCache {
|
|
|
return &MemCache{
|
|
|
- engine: cache.New(time.Hour, time.Minute*10),
|
|
|
+ engine: cache.New(memCacheDefaultExpired, memCacheCleanupInterval),
|
|
|
}
|
|
|
}
|