github.com/OrigamiWang/msd/micro@v0.0.0-20240229032328-b62246268db9/model/dao/redis.go (about)

     1  package dao
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"time"
     7  
     8  	"github.com/OrigamiWang/msd/micro/confparser"
     9  	"github.com/redis/go-redis/v9"
    10  )
    11  
    12  type RedisClient struct {
    13  	Client *redis.Client
    14  }
    15  
    16  func InitRedis(db *confparser.Database) *redis.Client {
    17  	addr := fmt.Sprintf("%s:%d", db.Host, db.Port)
    18  	return redis.NewClient(&redis.Options{
    19  		Addr:     addr,
    20  		Password: db.Password,
    21  		DB:       0,
    22  		Username: db.User,
    23  	})
    24  
    25  }
    26  func (rc *RedisClient) Get(key string) (interface{}, error) {
    27  	return rc.Client.Get(context.Background(), key).Result()
    28  }
    29  
    30  func (rc *RedisClient) Set(key string, value any, expireTime time.Duration) error {
    31  	return rc.Client.Set(context.Background(), key, value, expireTime).Err()
    32  }
    33  
    34  func (rc *RedisClient) Del(key string) error {
    35  	return rc.Client.Del(context.Background(), key).Err()
    36  }
    37  
    38  func (rc *RedisClient) RPush(key string, value any) error {
    39  	return rc.Client.RPush(context.Background(), key, value).Err()
    40  }
    41  
    42  func (rc *RedisClient) LRange(key string, start, end int64) ([]string, error) {
    43  	return rc.Client.LRange(context.Background(), key, start, end).Result()
    44  }
    45  
    46  // RangeAll is a shortcut of LRange with start = 0, end = -1
    47  func (rc *RedisClient) RangeAll(key string) ([]string, error) {
    48  	return rc.Client.LRange(context.Background(), key, 0, -1).Result()
    49  }
    50  
    51  func (rc *RedisClient) Ttl(key string) (time.Duration, error) {
    52  	return rc.Client.TTL(context.Background(), key).Result()
    53  }
    54  
    55  func (rc *RedisClient) Scan(match string, cnt int64) (keys []string, cursor uint64, err error) {
    56  	return rc.Client.Scan(context.Background(), 0, match, cnt).Result()
    57  }
    58  
    59  func (rc *RedisClient) Subsribe(channel string) {
    60  	rc.Client.Subscribe(context.Background(), channel)
    61  }