diff --git a/internal/app/common/service/cache.go b/internal/app/common/service/cache.go index 44f43b1..e25eee8 100644 --- a/internal/app/common/service/cache.go +++ b/internal/app/common/service/cache.go @@ -12,6 +12,7 @@ import ( "github.com/gogf/gf/v2/os/gctx" "github.com/tiger1103/gfast-cache/cache" "github.com/tiger1103/gfast/v3/internal/app/common/consts" + "sync" ) type ICache interface { @@ -23,7 +24,11 @@ type cacheImpl struct { prefix string } -var c = cacheImpl{} +var ( + c = cacheImpl{} + cacheContainer *cache.GfCache + lock = &sync.Mutex{} +) func Cache() ICache { var ( @@ -32,11 +37,19 @@ func Cache() ICache { ) prefix := g.Cfg().MustGet(ctx, "system.cache.prefix").String() model := g.Cfg().MustGet(ctx, "system.cache.model").String() - if model == consts.CacheModelRedis { - // redis - ch.GfCache = cache.NewRedis(prefix) - } else { - ch.GfCache = cache.New(prefix) + if cacheContainer == nil { + lock.Lock() + if cacheContainer == nil { + if model == consts.CacheModelRedis { + // redis + cacheContainer = cache.NewRedis(prefix) + } else { + // memory + cacheContainer = cache.New(prefix) + } + } + lock.Unlock() } + ch.GfCache = cacheContainer return &ch }