Bez popisu
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 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. d.mu.Lock()
  34. defer d.mu.Unlock()
  35. // 如果已存在,直接返回
  36. if factory := d.factories[name]; factory != nil {
  37. return factory, nil
  38. }
  39. dbConfig, _ := d.config.GetDbsConfig(name)
  40. if dbConfig == nil {
  41. return nil, fmt.Errorf("数据库配置 '%s' 不存在", name)
  42. }
  43. factory, err := createDBFactoryNew(dbConfig)
  44. if err != nil {
  45. return nil, fmt.Errorf("创建数据库工厂 '%s' 失败: %v", name, err)
  46. }
  47. d.factories[name] = factory
  48. return factory, nil
  49. }
  50. // Close 关闭所有数据库工厂
  51. func (d *DBSFactory) Close() {
  52. d.mu.Lock()
  53. defer d.mu.Unlock()
  54. for name, factory := range d.factories {
  55. log.Printf("Closing DBFactory '%s'...", name)
  56. factory.Close()
  57. }
  58. d.factories = make(map[string]*DBFactory)
  59. log.Println("All DBFactory instances closed.")
  60. }
  61. func (f *DBSFactory) GetName() string {
  62. return "DBSFactory"
  63. }