Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

连接数据库集群的疑问? #142

Open
T-TRz879 opened this issue Jul 17, 2024 · 0 comments
Open

连接数据库集群的疑问? #142

T-TRz879 opened this issue Jul 17, 2024 · 0 comments
Assignees

Comments

@T-TRz879
Copy link

请教连接数据库集群的用法

现在有三个数据库节点可连(分别是节点a,b,c)。

  1. 在初始化的时候我要先初始化a节点的连接。
  2. 用a节点连接的节点去添加plugin,plugin中的Sources和Replicas(感觉可以随便填)。
  3. 把a节点再填入Sources中会又初始化一次。
	masterDialectors := make([]gorm.Dialector, 0)
	slaveDialectors := make([]gorm.Dialector, 0)

	for i, master := range cfg.MySQL.Masters {
		connectionString := fmt.Sprintf("%s:%s@(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
			cfg.MySQL.User,
			cfg.MySQL.Pass,
			master,
			cfg.MySQL.DBName)

		dialector := mysql.New(mysql.Config{DSN: connectionString})

		if i == 0 {
			masterDialector = dialector
		} else {
			masterDialectors = append(masterDialectors, dialector)
		}
	}

	for _, slave := range cfg.MySQL.Slaves {
		if slave == "" {
			continue
		}

		connectionString := fmt.Sprintf("%s:%s@(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
			cfg.MySQL.User,
			cfg.MySQL.Pass,
			slave,
			cfg.MySQL.DBName)

		dialector := mysql.New(mysql.Config{DSN: connectionString})

		slaveDialectors = append(slaveDialectors, dialector)
	}

	gormConfig := &gorm.Config{
		SkipDefaultTransaction: true,
		Logger:                 logger.NewGorm(!cfg.Debug),
	}

	db, err = gorm.Open(masterDialector, gormConfig)
	if err != nil {
		log.Fatal("Fail to connect db", err)
	}

	err = db.Use(dbresolver.Register(dbresolver.Config{
		Sources:  masterDialectors,
		Replicas: slaveDialectors,
		Policy:   dbresolver.RandomPolicy{},
	}))
	if err != nil {
		log.Fatal("Fail to register master slave dbs", err)
	}

	db = db.Debug()

	rawDB, _ := db.DB()
	rawDB.SetMaxIdleConns(cfg.MySQL.MaxIdleConns)
	rawDB.SetMaxOpenConns(cfg.MySQL.MaxOpenConns)
	rawDB.SetConnMaxLifetime(time.Minute * 1)

设置连接数和连接的生命周期需要初始化结束后再设置,这。。。太别扭了。不知有无更优雅的方式

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants