mirror of
https://gitee.com/dromara/mayfly-go
synced 2025-11-04 08:20:25 +08:00
refactor: code optimization
This commit is contained in:
75
server/pkg/cache/cache.go
vendored
75
server/pkg/cache/cache.go
vendored
@@ -1,25 +1,72 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"mayfly-go/pkg/utils/anyx"
|
||||
"mayfly-go/pkg/utils/jsonx"
|
||||
"time"
|
||||
|
||||
"github.com/may-fly/cast"
|
||||
)
|
||||
|
||||
type Cache interface {
|
||||
// 添加缓存,如果缓存则返回错误
|
||||
Add(k string, v any) error
|
||||
// Set 设置缓存值
|
||||
// duration == -1 则为永久缓存
|
||||
Set(key string, value any, duration time.Duration) error
|
||||
|
||||
// 如果不存在则添加缓存值,否则直接返回
|
||||
AddIfAbsent(k string, v any)
|
||||
// Set2Str 将value转为字符串后设置缓存值
|
||||
Set2Str(key string, value any, duration time.Duration) error
|
||||
|
||||
// 如果存在则直接返回,否则调用getValue回调函数获取值并添加该缓存值
|
||||
// @return 缓存值
|
||||
ComputeIfAbsent(k string, getValueFunc func(string) (any, error)) (any, error)
|
||||
|
||||
// 获取缓存值,参数1为值,参数2->是否存在该缓存
|
||||
// Get 获取缓存值
|
||||
Get(k string) (any, bool)
|
||||
|
||||
// 缓存数量
|
||||
// GetJson 获取json缓存值,并将其解析到指定的结构体指针
|
||||
GetJson(k string, valPtr any) bool
|
||||
|
||||
// GetStr 获取字符串缓存值
|
||||
GetStr(k string) (string, bool)
|
||||
|
||||
// GetInt 获取int缓存值
|
||||
GetInt(k string) (int, bool)
|
||||
|
||||
// Delete 删除缓存
|
||||
Delete(key string) error
|
||||
|
||||
// DeleteByKeyPrefix 根据key前缀删除缓存
|
||||
DeleteByKeyPrefix(keyPrefix string) error
|
||||
|
||||
// Count 缓存数量
|
||||
Count() int
|
||||
|
||||
// 删除缓存
|
||||
Delete(k string)
|
||||
|
||||
// 清空所有缓存
|
||||
// Clear 清空所有缓存
|
||||
Clear()
|
||||
}
|
||||
|
||||
type defaultCache struct {
|
||||
c Cache // 具体的缓存实现, 用于实现一些接口的通用方法
|
||||
}
|
||||
|
||||
func (dc *defaultCache) Set2Str(key string, value any, duration time.Duration) error {
|
||||
return dc.c.Set(key, anyx.ToString(value), duration)
|
||||
}
|
||||
|
||||
func (dc *defaultCache) GetStr(k string) (string, bool) {
|
||||
if val, ok := dc.c.Get(k); ok {
|
||||
return cast.ToString(val), true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func (dc *defaultCache) GetInt(k string) (int, bool) {
|
||||
if val, ok := dc.c.Get(k); ok {
|
||||
return cast.ToInt(val), true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func (dc *defaultCache) GetJson(k string, valPtr any) bool {
|
||||
if val, ok := dc.GetStr(k); ok {
|
||||
jsonx.To(val, valPtr)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user