github.com/binbinly/pkg@v0.0.11-0.20240321014439-f4fbf666eb0f/storage/redis/redis.go (about)

     1  package redis
     2  
     3  import (
     4  	"context"
     5  	"log"
     6  
     7  	"github.com/alicebob/miniredis/v2"
     8  	"github.com/redis/go-redis/extra/redisotel/v9"
     9  	"github.com/redis/go-redis/v9"
    10  )
    11  
    12  const (
    13  	// Nil redis nil
    14  	Nil = redis.Nil
    15  	// Success redis成功标识
    16  	Success = 1
    17  	// DefaultDB default redis name
    18  	DefaultDB = "default"
    19  )
    20  
    21  // NewClient new a redis instance
    22  func NewClient(c *Config) (rdb *redis.Client, err error) {
    23  	if c.Url != "" {
    24  		opt, err := redis.ParseURL(c.Url)
    25  		if err != nil {
    26  			return nil, err
    27  		}
    28  		rdb = redis.NewClient(opt)
    29  	} else {
    30  		rdb = redis.NewClient(&redis.Options{
    31  			Addr:         c.Addr,
    32  			Username:     c.Username,
    33  			Password:     c.Password,
    34  			DB:           c.DB,
    35  			MinIdleConns: c.MinIdleConn,
    36  			DialTimeout:  c.DialTimeout,
    37  			ReadTimeout:  c.ReadTimeout,
    38  			WriteTimeout: c.WriteTimeout,
    39  			PoolSize:     c.PoolSize,
    40  			PoolTimeout:  c.PoolTimeout,
    41  		})
    42  	}
    43  	// check redis if is ok
    44  	if _, err = rdb.Ping(context.Background()).Result(); err != nil {
    45  		return nil, err
    46  	}
    47  
    48  	// hook tracing (using open telemetry)
    49  	if c.Trace {
    50  		if err = redisotel.InstrumentTracing(rdb); err != nil {
    51  			return nil, err
    52  		}
    53  	}
    54  
    55  	log.Println("init redis success by addr:", c.Addr)
    56  	return rdb, nil
    57  }
    58  
    59  // InitTestRedis 实例化一个可以用于单元测试的redis
    60  func InitTestRedis() *redis.Client {
    61  	mr, err := miniredis.Run()
    62  	if err != nil {
    63  		panic(err)
    64  	}
    65  	// 打开下面命令可以测试链接关闭的情况
    66  	// defer mr.Close()
    67  
    68  	rdb := redis.NewClient(&redis.Options{
    69  		Addr: mr.Addr(),
    70  	})
    71  
    72  	log.Println("mini redis addr:", mr.Addr())
    73  	return rdb
    74  }