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

72 lines
1.2 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 (
"mayfly-go/pkg/global"
"mayfly-go/pkg/rediscli"
"strconv"
"time"
)
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 {
2023-06-17 15:15:03 +08:00
if !useRedisCache() {
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
2022-12-26 20:53:07 +08:00
res, err := rediscli.Get(key)
if err != nil {
return ""
}
return res
}
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 {
global.Log.Error("获取缓存中的int值转换失败", err)
return 0
} else {
return intV
}
}
// 如果系统有设置redis信息则使用redis存否则存于本机内存。duration == -1则为永久缓存
func SetStr(key, value string, duration time.Duration) {
if !useRedisCache() {
checkCache()
tm.Add(key, value, duration)
2022-12-26 20:53:07 +08:00
return
}
2023-06-17 15:15:03 +08:00
rediscli.Set(key, value, duration)
2022-12-26 20:53:07 +08:00
}
// 删除指定key
func Del(key string) {
2023-06-17 15:15:03 +08:00
if !useRedisCache() {
checkCache()
tm.Delete(key)
return
}
rediscli.Del(key)
}
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
}
}
2023-06-17 15:15:03 +08:00
func useRedisCache() bool {
return rediscli.GetCli() != nil
}