

新闻资讯
技术学院beego 的 `cache.newcache("file", ...)` 不支持同一适配器(如 `"file"`)创建多个独立缓存实例;第二次调用会复用并重置首个实例,导致路径、配置混淆和数据错乱。
Beego 的缓存模块设计中,每个缓存适配器(adapter)在全局范围内仅允许存在一个实例。当你连续两次调用 cache.NewCache("file", config)(即使传入完全不同的配置 JSON),Beego 并不会创建两个独立的文件系统缓存对象,而是:
这正是你日志中看到的现象:
&{.../mycache ...} → 实际应为 MyCache 路径
&{.../othercache ...} → 两者都显示 othercache 路径 因为 MyCache 和 OtherCache 变量最终指向了*同一个被反复重置的 `fileCache实例**,所以后续所有Put/Get操作都作用于othercache目录 ——MyCache.Put("mykey", "myvalue")实际写入了.cache/othercache/,自然被OtherCache.Get("mykey")读回,而MyCache.Get("mykey")` 也读到相同内容。
Beego 允许通过 自定义适配器名 注册多个独立文件缓存。你需要先调用 cache.Register() 显式注册多个命名适配器:
package main
import (
"github.com/astaxie/beego/cache"
"log"
)
var
(
MyCache cache.Cache
OtherCache cache.Cache
err error
)
func Init() {
// 注册两个独立的 file 适配器(名称不同!)
cache.Register("file_my", &cache.FileCache{})
cache.Register("file_other", &cache.FileCache{})
// 使用各自注册的适配器名创建缓存
if MyCache, err = cache.NewCache("file_my", `{"CachePath":".cache/mycache","FileSuffix":".cache","DirectoryLevel":1,"EmbedExpiry":10}`); err != nil {
log.Fatal(err)
}
if OtherCache, err = cache.NewCache("file_other", `{"CachePath":".cache/othercache","FileSuffix":".cache","DirectoryLevel":1,"EmbedExpiry":10}`); err != nil {
log.Fatal(err)
}
}
func checkCache(c cache.Cache, k string) string {
if v := c.Get(k); v != nil {
return v.(string)
}
return ""
}
func writeCache(c cache.Cache, k, v string) {
if err := c.Put(k, v, 10); err != nil {
log.Println("Put error:", err)
}
}
func main() {
log.SetFlags(log.Lshortfile)
Init()
mykey := "mykey"
writeCache(MyCache, mykey, "myvalue")
writeCache(OtherCache, mykey, "othervalue")
log.Println("MyCache:", checkCache(MyCache, mykey)) // → "myvalue"
log.Println("OtherCache:", checkCache(OtherCache, mykey)) // → "othervalue"
}? 关键点:cache.Register("file_my", &cache.FileCache{}) 为每个缓存分配唯一标识符,确保 NewCache("file_my", ...) 和 NewCache("file_other", ...) 创建互不干扰的实例。
若不想注册新适配器,可只用一个 file 缓存,但为 key 添加前缀隔离:
const (
MyPrefix = "my:"
OtherPrefix = "other:"
)
func writeNamespaced(c cache.Cache, prefix, key, value string) {
c.Put(prefix+key, value, 10)
}
func readNamespaced(c cache.Cache, prefix, key string) string {
if v := c.Get(prefix + key); v != nil {
return v.(string)
}
return ""
}
// 使用时:writeNamespaced(MyCache, MyPrefix, "key", "val")优势是简单;缺点是无法物理隔离目录(删除需手动过滤 key),且 ClearAll() 会清空全部。
通过正确注册命名适配器,你既能保持目录级物理隔离(便于清理),又能彻底规避配置覆盖问题 —— 这不是你的代码错误,而是 Beego 缓存架构的明确约束。