|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- package util
-
- import (
- "encoding/json"
- "gim/internal/business/comm/utils"
- "gim/pkg/logger"
- "time"
-
- "github.com/go-redis/redis"
- jsoniter "github.com/json-iterator/go"
- )
-
- type RedisUtil struct {
- client *redis.Client
- }
-
- func NewRedisUtil(client *redis.Client) *RedisUtil {
- return &RedisUtil{client: client}
- }
-
- // Set 将指定值设置到redis中,使用json的序列化方式
- func (u *RedisUtil) Set(key string, value interface{}, duration time.Duration) error {
- bytes, err := jsoniter.Marshal(value)
- if err != nil {
- logger.Sugar.Error(err)
- return err
- }
-
- err = u.client.Set(key, bytes, duration).Err()
- if err != nil {
- logger.Sugar.Error(err)
- return err
- }
- return nil
- }
-
- // Get 从redis中读取指定值,使用json的反序列化方式
- func (u *RedisUtil) Get(key string, value interface{}) error {
- bytes, err := u.client.Get(key).Bytes()
- if err != nil {
- return err
- }
- err = jsoniter.Unmarshal(bytes, value)
- if err != nil {
- logger.Sugar.Error(err)
- return err
- }
- return nil
- }
-
- func (u *RedisUtil) HGetString(key string, HKey string) (string, error) {
- return u.client.Do("HGET", key, HKey).String()
- }
-
- func (u *RedisUtil) Exists(key string) bool {
- count, err := u.client.Do("EXISTS", key).Int()
- if count == 0 || err != nil {
- return false
- }
- return true
- }
-
- func (u *RedisUtil) HSet(key string, HKey string, data interface{}) (interface{}, error) {
- return u.client.HSet(key, HKey, data).Result()
- }
-
- func (u *RedisUtil) Expire(key string, ttl int) (interface{}, error) {
- return u.client.Do("EXPIRE", key, ttl).Result()
- }
-
- func (u *RedisUtil) Del(key string) (interface{}, error) {
- return u.client.Do("DEL", key).Result()
- }
-
- func (u *RedisUtil) Do(args ...interface{}) (reply interface{}, err error) {
- return u.client.Do(args...).String()
- }
-
- func (u *RedisUtil) SetEx(key string, data interface{}, ttl int) (reply interface{}, err error) {
- return u.client.Do("SETEX", key, ttl, data).Result()
- }
-
- func (u *RedisUtil) GetJson(key string, dst interface{}) error {
- b, err := utils.Bytes(u.client.Do("GET", key).Result())
- if err != nil {
- return err
- }
- if err = json.Unmarshal(b, dst); err != nil {
- return err
- }
- return nil
- }
-
- func (u *RedisUtil) SetJson(key string, data interface{}, ttl int) bool {
- c, err := json.Marshal(data)
- if err != nil {
- return false
- }
- if ttl < 1 {
- err = u.Set(key, c, time.Duration(ttl))
- } else {
- _, err = u.SetEx(key, c, ttl)
- }
- if err != nil {
- return false
- }
- return true
- }
|