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

     1  package redis
     2  
     3  import (
     4  	"log"
     5  	"sync"
     6  
     7  	"github.com/redis/go-redis/v9"
     8  )
     9  
    10  // manager redis连接管理器
    11  var manager *Manager
    12  
    13  // Manager define a redis manager
    14  type Manager struct {
    15  	mu sync.RWMutex
    16  
    17  	clients map[string]*redis.Client
    18  }
    19  
    20  // NewClient new a redis client
    21  func (m *Manager) NewClient(name string, c *Config) {
    22  	if name == "" {
    23  		name = DefaultDB
    24  	}
    25  	m.mu.RLock()
    26  	if _, ok := m.clients[name]; ok {
    27  		m.mu.RUnlock()
    28  		return
    29  	}
    30  	m.mu.RUnlock()
    31  
    32  	m.mu.Lock()
    33  	defer m.mu.Unlock()
    34  
    35  	rdb, err := NewClient(c)
    36  	if err != nil {
    37  		log.Fatalf("init redis client err:%v", err)
    38  	}
    39  	m.clients[name] = rdb
    40  }
    41  
    42  // GetClient get a redis client
    43  func (m *Manager) GetClient(name string) *redis.Client {
    44  	m.mu.RLock()
    45  	defer m.mu.RUnlock()
    46  
    47  	if c, ok := m.clients[name]; ok {
    48  		return c
    49  	}
    50  	return nil
    51  }
    52  
    53  // NewManager create a redis manager
    54  func NewManager() *Manager {
    55  	m := &Manager{
    56  		clients: make(map[string]*redis.Client),
    57  	}
    58  	manager = m
    59  	return m
    60  }
    61  
    62  // GetManager get a redis manager
    63  func GetManager() *Manager {
    64  	return manager
    65  }
    66  
    67  // GetClient get a redis client
    68  func GetClient(name string) *redis.Client {
    69  	return manager.GetClient(name)
    70  }