mysql组件
This commit is contained in:
parent
f56ff35039
commit
47463cd5fb
|
|
@ -14,4 +14,4 @@
|
||||||
|
|
||||||
# Dependency directories (remove the comment below to include it)
|
# Dependency directories (remove the comment below to include it)
|
||||||
# vendor/
|
# vendor/
|
||||||
|
go.sum
|
||||||
|
|
|
||||||
11
README.md
11
README.md
|
|
@ -1,3 +1,10 @@
|
||||||
# norm
|
# 组件应用标准结构定义库
|
||||||
|
|
||||||
组件应用标准结构定义库
|
#### 概述
|
||||||
|
1. 除特殊说明外,正常组件使用时在程序引导时调整用组件的Init进行配置初始化,使用New方法进行组件实例获取。
|
||||||
|
#### 组件实现
|
||||||
|
* MySQL
|
||||||
|
> "gorm.io/driver/mysql"
|
||||||
|
> "gorm.io/gorm"
|
||||||
|
> "gorm.io/gorm/logger"
|
||||||
|
> "gorm.io/plugin/dbresolver"
|
||||||
|
|
@ -0,0 +1,15 @@
|
||||||
|
module myschools.me/suguo/norm
|
||||||
|
|
||||||
|
go 1.17
|
||||||
|
|
||||||
|
require (
|
||||||
|
gorm.io/driver/mysql v1.1.2
|
||||||
|
gorm.io/gorm v1.21.14
|
||||||
|
gorm.io/plugin/dbresolver v1.1.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/go-sql-driver/mysql v1.6.0 // indirect
|
||||||
|
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||||
|
github.com/jinzhu/now v1.1.2 // indirect
|
||||||
|
)
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
package mysql
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gorm.io/driver/mysql"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/logger"
|
||||||
|
"gorm.io/plugin/dbresolver"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
_db *gorm.DB
|
||||||
|
_conf *Config
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
ConnString string
|
||||||
|
ConnMaxLifetime int64 //ConnMaxLifetime 最大连接时间,单位:小时
|
||||||
|
MaxIdleConns int
|
||||||
|
MaxOpenConns int
|
||||||
|
}
|
||||||
|
|
||||||
|
//Init mysql初始化
|
||||||
|
func Init(conf *Config) {
|
||||||
|
if conf != nil {
|
||||||
|
_conf = conf
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//New 创建实例
|
||||||
|
func New() (*gorm.DB, error) {
|
||||||
|
if _db != nil {
|
||||||
|
return _db, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("again!")
|
||||||
|
_db, err := gorm.Open(mysql.Open(_conf.ConnString), &gorm.Config{
|
||||||
|
SkipDefaultTransaction: true,
|
||||||
|
Logger: logger.Default.LogMode(logger.Silent),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
_db.Use(
|
||||||
|
dbresolver.Register(dbresolver.Config{
|
||||||
|
Sources: []gorm.Dialector{mysql.Open(_conf.ConnString)},
|
||||||
|
Replicas: []gorm.Dialector{mysql.Open(_conf.ConnString)},
|
||||||
|
Policy: dbresolver.RandomPolicy{},
|
||||||
|
}).SetConnMaxIdleTime(time.Hour).
|
||||||
|
SetConnMaxLifetime(time.Duration(_conf.ConnMaxLifetime) * time.Hour).
|
||||||
|
SetMaxIdleConns(_conf.MaxIdleConns).
|
||||||
|
SetMaxOpenConns(_conf.MaxOpenConns))
|
||||||
|
return _db, nil
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue