Przeglądaj źródła

fix:修复内存缓存-单例模式

yxh 3 lat temu
rodzic
commit
e554abe8cf
1 zmienionych plików z 19 dodań i 6 usunięć
  1. 19 6
      internal/app/common/service/cache.go

+ 19 - 6
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
 }