migrate from github
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/XingfenD/yoresee_doc/pkg/errs"
|
||||
redis "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var KVS *redis.Client
|
||||
|
||||
func NewRedisClient(cfg *RedisOptions) (*redis.Client, error) {
|
||||
if cfg == nil {
|
||||
return nil, errs.Detail(errs.ErrInitRedisClient, "redis options is nil")
|
||||
}
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
})
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if _, err := client.Ping(ctx).Result(); err != nil {
|
||||
_ = client.Close()
|
||||
return nil, errs.Wrap(errs.ErrInitRedisClient, err)
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func GetRedis() *redis.Client {
|
||||
return KVS
|
||||
}
|
||||
|
||||
func CloseRedis() error {
|
||||
if KVS == nil {
|
||||
return nil
|
||||
}
|
||||
return KVS.Close()
|
||||
}
|
||||
|
||||
func SetCache(ctx context.Context, key string, value interface{}, expiration time.Duration) error {
|
||||
return KVS.Set(ctx, key, value, expiration).Err()
|
||||
}
|
||||
|
||||
func GetCache(ctx context.Context, key string) (string, error) {
|
||||
return KVS.Get(ctx, key).Result()
|
||||
}
|
||||
|
||||
func DeleteCache(ctx context.Context, key string) error {
|
||||
return KVS.Del(ctx, key).Err()
|
||||
}
|
||||
|
||||
func ClearCacheByPattern(ctx context.Context, pattern string) error {
|
||||
keys, err := KVS.Keys(ctx, pattern).Result()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(keys) > 0 {
|
||||
return KVS.Del(ctx, keys...).Err()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func SetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) (bool, error) {
|
||||
return KVS.SetNX(ctx, key, value, expiration).Result()
|
||||
}
|
||||
|
||||
func SetCacheForever(ctx context.Context, key string, value interface{}) error {
|
||||
if err := KVS.Set(ctx, key, value, 0).Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return KVS.Persist(ctx, key).Err()
|
||||
}
|
||||
Reference in New Issue
Block a user