当前位置:网站首页>golang: Gorm配置Mysql多数据源
golang: Gorm配置Mysql多数据源
2022-07-30 05:51:00 【行人已】
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 // 非事务实例
Tx *gorm.Tx // 事务实例
Errors []error // 操作过程中记录的错误
}
// 数据库配置
type DBConfig struct {
DsName string // 数据源名称
Host string // 地址IP
Port string // 数据库端口
Database string // 数据库名称
Username string // 账号
Password string // 密码
}
// db连接
var (
MASTER = "DB1" // 默认主数据源
RDBs = map[string]*RDBManager{} // 初始化时加载数据源到集合
)
// 初始化多个数据库配置文件
func BuildByConfig(input ...DBConfig) {
if len(input) == 0 {
panic("数据源配置不能为空")
}
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)
边栏推荐
- Electron之初出茅庐——搭建环境并运行第一个程序
- 新人误删数据,组长巧用MySQL主从复制延迟挽回损失
- 手机端滚动至页面指定位置
- 阿里二面:Sentinel vs Hystrix 对比,如何选择?
- 云服务器零基础部署网站(保姆级教程)
- STL source code analysis: conceptual understanding of iterators, and code testing.
- PXE efficient mass network capacity
- 相机坐标系,世界坐标系,像素坐标系三者转换,以及OPENGLDEFocal Length和Opengl 的 Fov转换
- schur completement
- STL源码剖析:迭代器的概念理解,以及代码测试。
猜你喜欢

从追赶到超越,国产软件大显身手

引导过程与服务控制

Electron之初出茅庐——搭建环境并运行第一个程序

As a test leader, examine several aspects of job candidates

Distance calculation from space vertex to straight line and its source code

阿里二面:Redis有几种集群方案?我答了4种

MYSQL-GROUP BY 用法 全网最精,通熟易懂的话解释

Test Development Engineer Growth Diary 017 - The Life Cycle of a Bug

matlab机器学习_01

Process and Scheduled Task Management
随机推荐
Let the "label" content in Baidu map generator expand--solution
舒尔补(schur completement)
When does MySQL use table locks and when does it use row locks?
Electron之初出茅庐——搭建环境并运行第一个程序
mysql高阶语句(一)
Advanced multi-threading (CountDownLatch, deadlock, thread-safe collection class)
(GGG)JWT
UDP和TCP使用同一个端口,可行吗?
Redis下载与安装
The Society of Mind - Marvin Minsky
MongoDB-CUD without R
sql concat()函数
图解关系数据库设计思想,这也太形象了
Test Development Engineer Growth Diary 017 - The Life Cycle of a Bug
Test development engineer growth diary 016 - those things about the test
计算矩阵的逆源码(使用伴随矩阵,3×3的矩阵)
The calculation proof of the intersection of the space line and the plane and its source code
What new materials are used in the large aircraft C919?
The terminal connection tools, rolling Xshell
New material under the plastic restriction order - polylactic acid (PLA)