当前位置:网站首页>golang: Gorm configures Mysql multiple data sources
golang: Gorm configures Mysql multiple data sources
2022-07-30 08:02:00 【pedestrians have】
1、目录结构
test
--------------main.go
--------------setting.json
--------------common
------------------------common/mysql
------------------------common/mysql/gorm_mysql.go
------------------------common/mysql/mysql_setting.go
2、setting.json配置
{
"database": [
{
"DB1": {
"dsName": "db1",
"host": "127.0.0.1",
"port": "3306",
"username": "root",
"password": "",
"database": "数据库名称1",
"type": "mysql"
},
"DB2": {
"dsName": "db2",
"host": "127.0.0.1",
"port": "3306",
"username": "root",
"password": "",
"database": "数据库名称2",
"type": "mysql"
}
}
]
}
3、文件引入
go get -u gorm.io/gorm
go get -u gorm.io/gorm
4、读取Setting.go配置文件(mysql_setting.go)
package mysql
import (
"encoding/json"
"fmt"
"log"
"os"
)
func Init_MySqlFile() {
filePtr, err := os.Open("./setting.json")
if err != nil {
log.Printf("文件打开失败 [Err:%s]", err.Error())
return
}
defer filePtr.Close()
// 创建json解码器
info := AutoGenerated{}
decoder := json.NewDecoder(filePtr)
err = decoder.Decode(&info)
if err != nil {
fmt.Println("mysql解码失败", err.Error())
}
//初始化数据库
for _, v := range info.Database {
d1 := v.DB1
d2 := v.DB2
conf1 := DBConfig{
DsName: d1.DsName,
Host: d1.Host,
Port: d1.Port,
Database: d1.Database,
Username: d1.Username,
Password: d1.Password,
}
conf2 := DBConfig{
DsName: d2.DsName,
Host: d2.Host,
Port: d2.Port,
Database: d2.Database,
Username: d2.Username,
Password: d2.Password,
}
BuildByConfig(conf1)
BuildByConfig(conf2)
}
}
//--json转实体
type AutoGenerated struct {
Database []Database `json:"database"`
}
type DB1 struct {
DsName string `json:"dsName"`
Host string `json:"host"`
Port string `json:"port"`
Username string `json:"username"` // 账号
Password string `json:"password"`
Database string `json:"database"`
Type string `json:"type"`
}
type DB2 struct {
DsName string `json:"dsName"`
Host string `json:"host"`
Port string `json:"port"`
Username string `json:"username"` // 账号
Password string `json:"password"`
Database string `json:"database"`
Type string `json:"type"`
}
type Database struct {
DB1 DB1 `json:"DB1"`
DB2 DB2 `json:"DB2"`
}
5、配置MySql链接(gorm_mysql.go)
package mysql
import (
"fmt"
"log"
"os"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// 连接管理器
type RDBManager struct {
OpenTx bool // 是否开启事务
DsName string // 数据源名称
Db *gorm.DB // non-transactional instance
Tx *gorm.Tx // 事务实例
Errors []error // Errors logged during operation
}
// 数据库配置
type DBConfig struct {
DsName string // 数据源名称
Host string // 地址IP
Port string // 数据库端口
Database string // 数据库名称
Username string // 账号
Password string // 密码
}
// db连接
var (
MASTER = "DB1" // Default primary data source
RDBs = map[string]*RDBManager{} // Loads the data source into the collection during initialization
)
// Initialize multiple database configuration files
func BuildByConfig(input ...DBConfig) {
if len(input) == 0 {
panic("Datasource configuration cannot be empty")
}
for _, v := range input {
db, err := MysqlSetup(v)
if err != nil {
log.Printf("数据库链接失败 %s ", err.Error())
return
}
if len(v.DsName) == 0 {
v.DsName = MASTER
}
rdb := &RDBManager{
Db: db,
DsName: v.DsName,
}
RDBs[v.DsName] = rdb
}
}
// Setup 初始化连接
func MysqlSetup(conf DBConfig) (*gorm.DB, error) {
//启用打印日志
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // 慢 SQL 阈值
LogLevel: logger.Info, // Log level: Silent、Error、Warn、Info
Colorful: false, // 禁用彩色打印
},
)
// db = newConnection()
dbURI := fmt.Sprintf("%s:%[email protected](%s:%s)/%s?charset=utf8&parseTime=true",
conf.Username,
conf.Password,
conf.Host,
conf.Port,
conf.Database)
dialector := mysql.New(mysql.Config{
DSN: dbURI, // data source name
DefaultStringSize: 256, // default size for string fields
DisableDatetimePrecision: true, // disable datetime precision, which not supported before MySQL 5.6
DontSupportRenameIndex: true, // drop & create when rename index, rename index not supported before MySQL 5.7, MariaDB
DontSupportRenameColumn: true, // `change` when rename column, rename column not supported before MySQL 8, MariaDB
SkipInitializeWithVersion: false, // auto configure based on currently MySQL version
})
// conn, err := gorm.Open(dialector, &gorm.Config{
// Logger: newLogger,
// })
conn, err := gorm.Open(dialector, &gorm.Config{
Logger: newLogger,
})
if err != nil {
log.Print(err.Error())
return conn, err
}
sqlDB, err := conn.DB()
if err != nil {
log.Print("connect db server failed.")
}
sqlDB.SetMaxIdleConns(100) // 设置最大连接数
sqlDB.SetMaxOpenConns(100) // 设置最大的空闲连接数
sqlDB.SetConnMaxLifetime(3600)
return conn, nil
}
5、启动配置(main.go)
func main() {
//初始化数据库
mysql.Init_MySqlFile()
}
6、使用
import mysql "common/mysql"
db := mysql.RDBs["db2"]
var rr []实体类
result := db.Db.Where().Find(&rr)
边栏推荐
猜你喜欢

From catching up to surpassing, domestic software shows its talents

Ali Ermian: How many cluster solutions does Redis have?I answered 4

2020 ACM | MoFlow: An Invertible Flow Model for Generating Molecular Graphs

MySQL什么时候用表锁,什么时候用行锁?

STL源码剖析:迭代器的概念理解,以及代码测试。

云服务器零基础部署网站(保姆级教程)

Graphical relational database design ideas, this is too vivid

AI can identify race from X-rays, but no one knows why

The terminal connection tools, rolling Xshell

Calculate the inverse source of the matrix (using the adjoint matrix, a 3x3 matrix)
随机推荐
CTO说不建议我使用SELECT * ,这是为什么?
Go 结合Gin导出Mysql数据到Excel表格
debian problem
阿里二面:Sentinel vs Hystrix 对比,如何选择?
Station B collapsed, what would you do if you were the developer in charge that night?
Camera coordinate system, world coordinate system, pixel coordinate system conversion, and Fov conversion of OPENGLDEFocal Length and Opengl
Vue项目通过node连接MySQL数据库并实现增删改查操作
空间平面相交的直线的计算及其源码
使用navicat连接mysql数据库时常报的错误:2003、1698、1251
Let the "label" content in Baidu map generator expand--solution
When does MySQL use table locks and when does it use row locks?
Graphical relational database design ideas, this is too vivid
Boot process and service control
Electron使用romote报错 : Uncaught TypeError: Cannot read property ‘BrowserWindow‘ of undefined
舒尔补(schur completement)
五号黯区靶场 mysql 注入之limit注入记录
空间顶点到平面的距离计算的证明及其源码
Headline 2: there are several kinds of common SQL errors in MySQL usage?
C#的访问修饰符,声明修饰符,关键字有哪些?扫盲篇
LVM and disk quotas