gitee.com/woood2/luca@v1.0.4/internal/cache/redis.go (about)

     1  package cache
     2  
     3  import (
     4  	"context"
     5  	"gitee.com/woood2/luca/internal/conf"
     6  	"github.com/go-redis/redis/v8"
     7  	"log"
     8  	"strings"
     9  	"sync"
    10  	"time"
    11  )
    12  
    13  var globalRedis *RedisCache
    14  
    15  func SetRedis(c *RedisCache) {
    16  	globalRedis = c
    17  }
    18  
    19  func Redis() *RedisCache {
    20  	return globalRedis
    21  }
    22  
    23  func NewRedis(c *conf.Redis) *RedisCache {
    24  	var client redis.UniversalClient
    25  	s := strings.Split(c.Addr, ",")
    26  	for i, v := range s {
    27  		s[i] = strings.TrimSpace(v)
    28  	}
    29  	if len(s) == 1 {
    30  		client = redis.NewClient(&redis.Options{
    31  			Addr:     c.Addr,
    32  			Password: c.Pwd,
    33  			PoolSize: c.PoolSize, //Default is 10 connections per every CPU as reported by runtime.NumCPU.
    34  			MinIdleConns: c.MinIdleConns,
    35  			DB:       0, // use default DB
    36  		})
    37  	}
    38  	if len(s) > 1 {
    39  		client = redis.NewClusterClient(&redis.ClusterOptions{
    40  			Addrs:    s,
    41  			Password: c.Pwd,
    42  			PoolSize: c.PoolSize,
    43  			MinIdleConns: c.MinIdleConns,
    44  		})
    45  	}
    46  	if client != nil {
    47  		return &RedisCache{
    48  			Protector: Protector{
    49  				lock:  sync.Mutex{},
    50  				apply: make(map[string]chan struct{}),
    51  			},
    52  			Client: client,
    53  		}
    54  	}
    55  	log.Panicf("invalid redis addr: %s\n", c.Addr)
    56  	return nil
    57  }
    58  
    59  
    60  type RedisCache struct {
    61  	Protector
    62  	MissHolder
    63  	Client redis.UniversalClient
    64  }
    65  
    66  func (c *RedisCache) Get(k string, p interface{}) error {
    67  	v, err := c.Client.Get(context.Background(), k).Result()
    68  	if err == redis.Nil {
    69  		return Miss
    70  	}
    71  	if err != nil {
    72  		return err
    73  	}
    74  	Deserialize(v, p)
    75  	return nil
    76  }
    77  
    78  func (c *RedisCache) Set(k string, v interface{}, d time.Duration) error {
    79  	return c.Client.Set(context.Background(), k, Serialize(v), d).Err()
    80  }