github.com/binbinly/pkg@v0.0.11-0.20240321014439-f4fbf666eb0f/cache/cache.go (about) 1 package cache 2 3 import ( 4 "context" 5 "errors" 6 "strings" 7 "time" 8 ) 9 10 const ( 11 // DefaultPrefix 默认缓存前缀 12 DefaultPrefix = "cache:" 13 // DefaultExpireTime 默认过期时间 14 DefaultExpireTime = time.Hour * 24 15 // DefaultNotFoundExpireTime 结果为空时的过期时间 1分钟, 常用于数据为空时的缓存时间(缓存穿透) 16 DefaultNotFoundExpireTime = time.Minute 17 // NotFoundPlaceholder . 18 NotFoundPlaceholder = "*" 19 ) 20 21 var ( 22 // ErrPlaceholder 空数据标识 23 ErrPlaceholder = errors.New("cache: placeholder") 24 // ErrSetMemoryWithNotFound 设置内存缓存时key不存在 25 ErrSetMemoryWithNotFound = errors.New("cache: set memory cache err for not found") 26 ) 27 28 // Cache 定义cache驱动接口 29 type Cache interface { 30 Set(ctx context.Context, key string, val any, expiration time.Duration) error 31 Get(ctx context.Context, key string, val any) error 32 MultiSet(ctx context.Context, valMap map[string]any, expiration time.Duration) error 33 MultiGet(ctx context.Context, keys []string, valueMap any, newObject func() any) error 34 Del(ctx context.Context, keys ...string) error 35 SetCacheWithNotFound(ctx context.Context, key string) error 36 } 37 38 // BuildCacheKey 构建一个带有前缀的缓存key 39 func BuildCacheKey(prefix string, key string) (cacheKey string, err error) { 40 if key == "" { 41 return "", errors.New("[cache] key should not be empty") 42 } 43 44 cacheKey = key 45 if prefix != "" { 46 cacheKey, err = strings.Join([]string{prefix, key}, ":"), nil 47 } 48 49 return 50 }