当前位置:网站首页>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)
边栏推荐
- 和AI一起玩儿剧本杀:居然比我还入戏
- Distance calculation from space vertex to straight line and its source code
- Playing script killing with AI: actually more involved than me
- Go 使用 freecache 缓存
- How to use Swagger, say goodbye to postman
- PXE efficient mass network capacity
- ArrayList
- 预测人们对你的第一印象,“AI颜狗”的诞生
- RAID disk array
- Process and Scheduled Task Management
猜你喜欢
Boot process and service control
2020年度总结——品曾经,明得失,展未来
DNS domain name resolution services
What are the access modifiers, declaration modifiers, and keywords in C#?Literacy articles
MySQL master-slave replication configuration construction, one step in place
redis实现分布式锁的原理
从追赶到超越,国产软件大显身手
Polygon 3D(三维平面多边形)的法向量的计算(MeshLab默认的计算)
Ali two sides: List several tips for Api interface optimization
Ali Ermian: How many cluster solutions does Redis have?I answered 4
随机推荐
No, the Log4j vulnerability hasn't been fully fixed yet?
Table with tens of millions of data, how to query the fastest?
五号黯区靶场 mysql 注入之limit注入记录
window.open()的用法,js打开新窗体
this与super
UDP和TCP使用同一个端口,可行吗?
bean的生命周期
Go 使用mencached缓存
Electron之初出茅庐——搭建环境并运行第一个程序
Redis 如何实现防止超卖和库存扣减操作?
Electron使用romote报错 : Uncaught TypeError: Cannot read property ‘BrowserWindow‘ of undefined
Required request body is missing problem solving
阿里二面:Redis有几种集群方案?我答了4种
(GGG)JWT
sizeof
go : create database records using gorm
和AI一起玩儿剧本杀:居然比我还入戏
Electron之初出茅庐——搭建环境并运行第一个程序
Upload file -- file type, picture type, document type, video type, compressed package type
2020 数学建模之旅