gitee.com/h79/goutils@v1.22.10/dao/redis/redis.go (about)

     1  package redis
     2  
     3  import (
     4  	"context"
     5  	commonconfig "gitee.com/h79/goutils/common/config"
     6  	commonoption "gitee.com/h79/goutils/common/option"
     7  	"gitee.com/h79/goutils/common/result"
     8  	"gitee.com/h79/goutils/dao/config"
     9  	"github.com/go-redis/redis/v8"
    10  	"go.uber.org/zap"
    11  )
    12  
    13  var _ Client = (*Connector)(nil)
    14  
    15  type Connector struct {
    16  	selectName string
    17  	clientMap  map[string]*Adapter
    18  }
    19  
    20  func NewRedis(conf []config.Redis, opts ...commonoption.Option) (Client, error) {
    21  	zap.L().Info("Redis", zap.Any("Config", conf))
    22  	clients := &Connector{clientMap: map[string]*Adapter{}}
    23  
    24  	for i := range conf {
    25  		adapter, err := NewAdapter(conf[i].Name, &conf[i].Master, &conf[i].Sentinel, &conf[i].Cluster, opts...)
    26  		if err != nil {
    27  			continue
    28  		}
    29  		clients.clientMap[conf[i].Name] = adapter
    30  	}
    31  
    32  	if len(clients.clientMap) > 0 && len(conf) > 0 && conf[0].Logger.LogLevel > 0 {
    33  		log := &Logger{
    34  			RedisLogger: conf[0].Logger,
    35  		}
    36  		redis.SetLogger(log)
    37  		if commonconfig.RegisterConfig != nil {
    38  			commonconfig.RegisterConfig("Redis|"+conf[0].Name, log.handlerConfig)
    39  		}
    40  	}
    41  	return clients, nil
    42  }
    43  
    44  func (c *Connector) Get(name string) (Redis, error) {
    45  	if len(name) == 0 {
    46  		name = c.selectName
    47  	}
    48  	cli, exists := c.clientMap[name]
    49  	if exists == true {
    50  		return cli, nil
    51  	}
    52  	return nil, result.Error(result.ErrNotFound, "Not found")
    53  }
    54  
    55  func (c *Connector) Close(name string) error {
    56  	if len(name) == 0 {
    57  		name = c.selectName
    58  	}
    59  	cli, exists := c.clientMap[name]
    60  	if exists == true {
    61  		return cli.client.Close()
    62  	}
    63  	return nil
    64  }
    65  
    66  func (c *Connector) CloseAll() {
    67  	for _, cli := range c.clientMap {
    68  		_ = cli.client.Close()
    69  	}
    70  	c.clientMap = nil
    71  }
    72  
    73  func (c *Connector) Select(name string) {
    74  	c.selectName = name
    75  }
    76  
    77  func (c *Connector) GetSelector() string {
    78  	return c.selectName
    79  }
    80  
    81  func (c *Connector) SelectDB(name string, index int) error {
    82  	cli, err := c.Get(name)
    83  	if err != nil {
    84  		return err
    85  	}
    86  	_, err = cli.Rds().Do(context.Background(), "select", index).Result()
    87  	return err
    88  }