多活高可用服务 MAS-gorm

时间:2024-11-29 09:14:12

gorm

创建gorm.io/gorm包gorm.DB数据源,进行mysql操作

依赖引入,配置文件或配置信息修改参考原生DB

初始化创建gorm数据源DevSporeGorm,后续执行Mysql相关操作。

  • 配置文件方式创建。
    import (
        "log"
    
        _ "github.com/huaweicloud/devcloud-go/sql-driver/mysql"
        "gorm.io/driver/mysql"
        "gorm.io/gorm"
    )
    var (
        DevSporeGorm *gorm.DB
        err error
    )
    func init() {
        DevSporeGorm, err = gorm.Open(mysql.New(
          mysql.Config{DriverName: "devspore_mysql", DSN: "./conf/resources/config_mysql.yaml"},
        ))
        if err != nil {
            log.Fatalln(err)
        }
    }
  • 配置信息方式创建。
    import (
        "log"
    
        devspore "github.com/huaweicloud/devcloud-go/sql-driver/mysql"
        "gorm.io/driver/mysql"
        "gorm.io/gorm"
    )
    var (
        DevSporeGorm *gorm.DB
        err error
    )
    func init() {
        devspore.SetClusterConfiguration(mysqlConfiguration())
        DevSporeGorm, err = gorm.Open(mysql.New(mysql.Config{DriverName: "devspore_mysql", DSN: ""}))
        if err != nil {
            log.Fatalln(err)
        }
    }
support.huaweicloud.com/devg-mas/mas-devg-0055.html