From c456d1249e41824f9134b057df7744ac3ce84223 Mon Sep 17 00:00:00 2001 From: lixxxww <941403820@qq.com> Date: Tue, 23 Jan 2024 11:42:22 +0000 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4kit/rediscli?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: lixxxww <941403820@qq.com> --- kit/rediscli/rediscli.go | 52 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 kit/rediscli/rediscli.go diff --git a/kit/rediscli/rediscli.go b/kit/rediscli/rediscli.go new file mode 100644 index 0000000..f3bce49 --- /dev/null +++ b/kit/rediscli/rediscli.go @@ -0,0 +1,52 @@ +package rediscli + +import ( + "context" + "fmt" + "github.com/go-redis/redis/v8" + "time" +) + +type RedisDB struct { + *redis.Client +} + +func NewRedisClient(host, password string, port, db int) (*RedisDB, error) { + rdb := redis.NewClient(&redis.Options{ + Addr: fmt.Sprintf("%s:%d", host, port), + Password: password, + DB: db, + }) + + if _, err := rdb.Ping(context.Background()).Result(); err != nil { + return nil, err + } + + return &RedisDB{ + Client: rdb, + }, nil +} + +func (rdb *RedisDB) HGet(key, field string, obj interface{}) error { + return rdb.Client.HGet(context.Background(), key, field).Scan(obj) +} + +func (rdb *RedisDB) HSet(key, field string, val interface{}) error { + return rdb.Client.HSet(context.Background(), key, field, val).Err() +} + +func (rdb *RedisDB) HDel(key string, fields ...string) error { + return rdb.Client.HDel(context.Background(), key, fields...).Err() +} + +func (rdb *RedisDB) Get(key string, obj interface{}) error { + return rdb.Client.Get(context.Background(), key).Scan(obj) +} + +func (rdb *RedisDB) GetResult(key string) (string, error) { + return rdb.Client.Get(context.Background(), key).Result() +} + +func (rdb *RedisDB) Set(key string, val interface{}, expir time.Duration) error { + return rdb.Client.Set(context.Background(), key, val, expir).Err() +}