Files
mayfly-go/server/pkg/cache/str_cache.go

112 lines
2.4 KiB
Go
Raw Normal View History

2022-12-26 20:53:07 +08:00
package cache
2023-06-17 15:15:03 +08:00
import (
2024-03-29 21:40:26 +08:00
"encoding/json"
"mayfly-go/pkg/logx"
2023-06-17 15:15:03 +08:00
"mayfly-go/pkg/rediscli"
2024-03-29 21:40:26 +08:00
"mayfly-go/pkg/utils/anyx"
2023-06-17 15:15:03 +08:00
"strconv"
"strings"
2023-06-17 15:15:03 +08:00
"time"
"github.com/may-fly/cast"
2023-06-17 15:15:03 +08:00
)
2022-12-26 20:53:07 +08:00
2023-06-17 15:15:03 +08:00
var tm *TimedCache
2022-12-26 20:53:07 +08:00
// 如果系统有设置redis信息则从redis获取否则本机内存获取
func GetStr(key string) string {
2024-01-17 17:02:15 +08:00
if !UseRedisCache() {
2023-06-17 15:15:03 +08:00
checkCache()
val, _ := tm.Get(key)
if val == nil {
return ""
}
return val.(string)
2022-12-26 20:53:07 +08:00
}
2023-06-17 15:15:03 +08:00
if res, err := rediscli.Get(key); err == nil {
return res
2022-12-26 20:53:07 +08:00
}
return ""
2022-12-26 20:53:07 +08:00
}
2023-06-17 15:15:03 +08:00
func GetInt(key string) int {
val := GetStr(key)
if val == "" {
return 0
}
if intV, err := strconv.Atoi(val); err != nil {
logx.Error("获取缓存中的int值转换失败", err)
2023-06-17 15:15:03 +08:00
return 0
} else {
return intV
}
}
2024-03-29 21:40:26 +08:00
// Get 获取缓存值并使用json反序列化。返回是否获取成功。若不存在或者解析失败则返回false
func Get[T any](key string, valPtr T) bool {
strVal := GetStr(key)
if strVal == "" {
return false
}
if err := json.Unmarshal([]byte(strVal), valPtr); err != nil {
logx.Errorf("json转换缓存中的值失败: %v", err)
return false
}
return true
}
// SetStr 如果系统有设置redis信息则使用redis存否则存于本机内存。duration == -1则为永久缓存
func SetStr(key, value string, duration time.Duration) error {
2024-01-17 17:02:15 +08:00
if !UseRedisCache() {
2023-06-17 15:15:03 +08:00
checkCache()
return tm.Add(key, value, duration)
2022-12-26 20:53:07 +08:00
}
return rediscli.Set(key, value, duration)
2022-12-26 20:53:07 +08:00
}
// Set 如果系统有设置redis信息则使用redis存否则存于本机内存。duration == -1则为永久缓存
2024-03-29 21:40:26 +08:00
func Set(key string, value any, duration time.Duration) error {
strVal := anyx.ToString(value)
if !UseRedisCache() {
checkCache()
return tm.Add(key, strVal, duration)
}
return rediscli.Set(key, strVal, duration)
}
// 删除指定key
func Del(key string) {
2024-01-17 17:02:15 +08:00
if !UseRedisCache() {
2023-06-17 15:15:03 +08:00
checkCache()
tm.Delete(key)
return
}
rediscli.Del(key)
}
// DelByKeyPrefix 根据key前缀删除满足前缀的所有缓存
func DelByKeyPrefix(keyPrefix string) error {
if !UseRedisCache() {
checkCache()
for key := range tm.Items() {
if strings.HasPrefix(cast.ToString(key), keyPrefix) {
tm.Delete(key)
}
}
return nil
}
return rediscli.DelByKeyPrefix(keyPrefix)
}
2024-01-17 17:02:15 +08:00
func UseRedisCache() bool {
return rediscli.GetCli() != nil
}
2023-06-17 15:15:03 +08:00
func checkCache() {
if tm == nil {
tm = NewTimedCache(time.Minute*time.Duration(5), 30*time.Second)
2022-12-26 20:53:07 +08:00
}
}