Files
service-common/db/redis/client.go

87 lines
2.1 KiB
Go

package redis
import (
"context"
"git.hlsq.asia/mmorpg/service-common/config"
"git.hlsq.asia/mmorpg/service-common/log"
"github.com/redis/go-redis/v9"
"time"
)
var instance *Client
type Client struct {
cli *redis.Client
}
func Init(cfg *config.RedisConfig) error {
client := redis.NewClient(&redis.Options{
Addr: cfg.Addr,
Password: cfg.Password,
DB: cfg.DB,
})
instance = &Client{
cli: client,
}
cacheInstance = &CacheClient{
cli: client,
}
if logger := log.GetLogger(); logger != nil {
cacheInstance.logger = logger.Named("CACHE")
}
_, err := client.Ping(context.Background()).Result()
return err
}
func Close() error {
if instance != nil && instance.cli != nil {
return instance.cli.Close()
}
return nil
}
func GetClient() *Client {
return instance
}
func (c *Client) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.StatusCmd {
return c.cli.Set(ctx, key, value, expiration)
}
func (c *Client) SetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.BoolCmd {
return c.cli.SetNX(ctx, key, value, expiration)
}
func (c *Client) Get(ctx context.Context, key string) *redis.StringCmd {
return c.cli.Get(ctx, key)
}
func (c *Client) HSet(ctx context.Context, key string, values ...interface{}) *redis.IntCmd {
return c.cli.HSet(ctx, key, values...)
}
func (c *Client) HGet(ctx context.Context, key, field string) *redis.StringCmd {
return c.cli.HGet(ctx, key, field)
}
func (c *Client) HGetAll(ctx context.Context, key string) *redis.MapStringStringCmd {
return c.cli.HGetAll(ctx, key)
}
func (c *Client) HDel(ctx context.Context, key string, fields ...string) *redis.IntCmd {
return c.cli.HDel(ctx, key, fields...)
}
func (c *Client) Pipeline() redis.Pipeliner {
return c.cli.Pipeline()
}
func (c *Client) ScriptLoad(ctx context.Context, script string) *redis.StringCmd {
return c.cli.ScriptLoad(ctx, script)
}
func (c *Client) EvalSha(ctx context.Context, sha1 string, keys []string, args ...interface{}) *redis.Cmd {
return c.cli.EvalSha(ctx, sha1, keys, args...)
}