暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dbs_factory.go 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package database
  2. import (
  3. "fmt"
  4. "log"
  5. "sync"
  6. "git.x2erp.com/qdy/go-base/config"
  7. )
  8. // DBSFactory 多数据库工厂管理器
  9. type DBSFactory struct {
  10. factories map[string]*DBFactory // 存储多个数据库工厂
  11. config config.IConfig
  12. mu sync.RWMutex // 并发安全锁
  13. }
  14. var (
  15. // 全局单例的多数据库工厂管理器
  16. dbsFactoryInstance *DBSFactory
  17. dbsFactoryInstanceOnce sync.Once
  18. )
  19. // CreateDBSFactory 获取多数据库工厂管理器单例
  20. func CreateDBSFactory(cfg config.IConfig) *DBSFactory {
  21. dbsFactoryInstanceOnce.Do(func() {
  22. dbsFactoryInstance = &DBSFactory{
  23. factories: make(map[string]*DBFactory),
  24. config: cfg,
  25. }
  26. log.Println("DBSFactory initialized.")
  27. })
  28. return dbsFactoryInstance
  29. }
  30. // ========== DBSFactory 实例方法 ==========
  31. // CreateDBFactory 创建指定名称的数据库工厂
  32. func (d *DBSFactory) CreateDBFactory(name string) (*DBFactory, error) {
  33. // 第一次检查(不加锁),如果存在直接返回
  34. d.mu.RLock()
  35. if factory := d.factories[name]; factory != nil {
  36. d.mu.RUnlock()
  37. return factory, nil
  38. }
  39. d.mu.RUnlock()
  40. // 加锁进行创建
  41. d.mu.Lock()
  42. defer d.mu.Unlock()
  43. // 第二次检查(加锁后),防止并发创建
  44. if factory := d.factories[name]; factory != nil {
  45. return factory, nil
  46. }
  47. dbConfig, _ := d.config.GetDbsConfig(name)
  48. if dbConfig == nil {
  49. return nil, fmt.Errorf("数据库配置 '%s' 不存在", name)
  50. }
  51. factory, err := createDBFactoryNew(dbConfig)
  52. if err != nil {
  53. return nil, fmt.Errorf("创建数据库工厂 '%s' 失败: %v", name, err)
  54. }
  55. d.factories[name] = factory
  56. return factory, nil
  57. }
  58. // Close 关闭所有数据库工厂
  59. func (d *DBSFactory) Close() {
  60. d.mu.Lock()
  61. defer d.mu.Unlock()
  62. for name, factory := range d.factories {
  63. log.Printf("Closing DBFactory '%s'...", name)
  64. factory.Close()
  65. }
  66. d.factories = make(map[string]*DBFactory)
  67. log.Println("All DBFactory instances closed.")
  68. }
  69. func (f *DBSFactory) GetName() string {
  70. return "DBSFactory"
  71. }