cache/redis.go

96 lines
2.1 KiB
Go

// Package cache ...
//
// Description : cache ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-06-21 14:18
package cache
import (
"context"
cacheAbstract "git.zhangdeman.cn/zhangdeman/cache/abstract"
"git.zhangdeman.cn/zhangdeman/redis"
)
var (
RedisClient = &Redis{}
)
// Redis 基于redis缓存
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:19 2023/3/21
type Redis struct {
}
// Exist 缓存是否存在
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:02 2024/6/21
func (r *Redis) Exist(ctx context.Context, instanceFlag string, key string) (bool, error) {
if nil == ctx {
ctx = context.Background()
}
res := redis.Wrapper.Exist(ctx, instanceFlag, key)
return res.Result == "1", res.Err
}
// Set 设置缓存
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:42 2023/3/25
func (r *Redis) Set(ctx context.Context, instanceFlag string, key string, value string, ttl int64) error {
if nil == ctx {
ctx = context.Background()
}
return redis.Wrapper.SetEx(ctx, instanceFlag, key, value, ttl, false).Err
}
// Get 获取redis中的原始数据
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 17:52 2023/4/26
func (r *Redis) Get(ctx context.Context, instanceFlag string, key string) (string, error) {
if nil == ctx {
ctx = context.Background()
}
res := redis.Wrapper.Get(ctx, instanceFlag, key)
return res.Result, res.Err
}
// Delete 删除缓存
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:41 2023/3/25
func (r *Redis) Delete(ctx context.Context, instanceFlag string, key string) error {
if nil == ctx {
ctx = context.Background()
}
return redis.Wrapper.Del(ctx, instanceFlag, key).Err
}
// GetWithParse ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:26 2024/6/21
func (r *Redis) GetWithParse(ctx context.Context, cacheInstanceFlag string, key string, parseFunc cacheAbstract.ResultParseFunc) (string, error) {
var (
res string
err error
)
if res, err = r.Get(ctx, cacheInstanceFlag, key); nil != err {
return "", err
}
if nil == parseFunc {
return res, nil
}
return res, parseFunc(res)
}