github.com/cloudreve/Cloudreve/v3@v3.0.0-20240224133659-3edb00a6484c/pkg/cache/driver.go (about) 1 package cache 2 3 import ( 4 "encoding/gob" 5 "github.com/cloudreve/Cloudreve/v3/pkg/conf" 6 "github.com/cloudreve/Cloudreve/v3/pkg/util" 7 "github.com/gin-gonic/gin" 8 ) 9 10 func init() { 11 gob.Register(map[string]itemWithTTL{}) 12 } 13 14 // Store 缓存存储器 15 var Store Driver = NewMemoStore() 16 17 // Init 初始化缓存 18 func Init() { 19 if conf.RedisConfig.Server != "" && gin.Mode() != gin.TestMode { 20 Store = NewRedisStore( 21 10, 22 conf.RedisConfig.Network, 23 conf.RedisConfig.Server, 24 conf.RedisConfig.User, 25 conf.RedisConfig.Password, 26 conf.RedisConfig.DB, 27 ) 28 } 29 } 30 31 // Restore restores cache from given disk file 32 func Restore(persistFile string) { 33 if err := Store.Restore(persistFile); err != nil { 34 util.Log().Warning("Failed to restore cache from disk: %s", err) 35 } 36 } 37 38 func InitSlaveOverwrites() { 39 err := Store.Sets(conf.OptionOverwrite, "setting_") 40 if err != nil { 41 util.Log().Warning("Failed to overwrite database setting: %s", err) 42 } 43 } 44 45 // Driver 键值缓存存储容器 46 type Driver interface { 47 // 设置值,ttl为过期时间,单位为秒 48 Set(key string, value interface{}, ttl int) error 49 50 // 取值,并返回是否成功 51 Get(key string) (interface{}, bool) 52 53 // 批量取值,返回成功取值的map即不存在的值 54 Gets(keys []string, prefix string) (map[string]interface{}, []string) 55 56 // 批量设置值,所有的key都会加上prefix前缀 57 Sets(values map[string]interface{}, prefix string) error 58 59 // 删除值 60 Delete(keys []string, prefix string) error 61 62 // Save in-memory cache to disk 63 Persist(path string) error 64 65 // Restore cache from disk 66 Restore(path string) error 67 } 68 69 // Set 设置缓存值 70 func Set(key string, value interface{}, ttl int) error { 71 return Store.Set(key, value, ttl) 72 } 73 74 // Get 获取缓存值 75 func Get(key string) (interface{}, bool) { 76 return Store.Get(key) 77 } 78 79 // Deletes 删除值 80 func Deletes(keys []string, prefix string) error { 81 return Store.Delete(keys, prefix) 82 } 83 84 // GetSettings 根据名称批量获取设置项缓存 85 func GetSettings(keys []string, prefix string) (map[string]string, []string) { 86 raw, miss := Store.Gets(keys, prefix) 87 88 res := make(map[string]string, len(raw)) 89 for k, v := range raw { 90 res[k] = v.(string) 91 } 92 93 return res, miss 94 } 95 96 // SetSettings 批量设置站点设置缓存 97 func SetSettings(values map[string]string, prefix string) error { 98 var toBeSet = make(map[string]interface{}, len(values)) 99 for key, value := range values { 100 toBeSet[key] = interface{}(value) 101 } 102 return Store.Sets(toBeSet, prefix) 103 }