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

     1  package orm
     2  
     3  import (
     4  	"sync"
     5  
     6  	"gorm.io/gorm"
     7  )
     8  
     9  // manager db连接管理器
    10  var manager *Manager
    11  
    12  // Manager define a db manager
    13  type Manager struct {
    14  	mu sync.RWMutex
    15  
    16  	clients map[string]*gorm.DB
    17  }
    18  
    19  // InitClient init a redis client
    20  func (m *Manager) InitClient(name string, c *Config) {
    21  	if name == "" {
    22  		name = "default"
    23  	}
    24  	m.mu.RLock()
    25  	if _, ok := m.clients[name]; ok {
    26  		m.mu.RUnlock()
    27  		return
    28  	}
    29  	m.mu.RUnlock()
    30  
    31  	m.mu.Lock()
    32  	defer m.mu.Unlock()
    33  
    34  	m.clients[name] = NewDB(c)
    35  }
    36  
    37  // GetClient get a redis client
    38  func (m *Manager) GetClient(name string) *gorm.DB {
    39  	m.mu.RLock()
    40  	defer m.mu.RUnlock()
    41  
    42  	if c, ok := m.clients[name]; ok {
    43  		return c
    44  	}
    45  	return nil
    46  }
    47  
    48  // NewRManager create a redis manager
    49  func NewRManager() *Manager {
    50  	m := &Manager{
    51  		clients: make(map[string]*gorm.DB),
    52  	}
    53  	manager = m
    54  	return m
    55  }
    56  
    57  // GetManager get a redis manager
    58  func GetManager() *Manager {
    59  	return manager
    60  }
    61  
    62  // GetClient get a redis client
    63  func GetClient(name string) *gorm.DB {
    64  	return manager.GetClient(name)
    65  }