Ai
1 Star 0 Fork 0

eden-framework/eden-framework

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
mysql.go 1.79 KB
一键复制 编辑 原始数据 按行查看 历史
文兄 提交于 2023-05-12 23:03 +08:00 . feat. 支持nacos
package mysql
import (
"fmt"
"gitee.com/eden-framework/envconfig"
"gitee.com/eden-framework/sqlx"
"gitee.com/eden-framework/sqlx/mysqlconnector"
"io"
"net/url"
"time"
)
type MySQL struct {
Name string
Host string
Port int
User string
Password envconfig.Password
Extra string
PoolSize int
ConnMaxLifetime envconfig.Duration
Retry
Database *sqlx.Database `json:"-" ignored:"true"`
*sqlx.DB `json:"-" ignored:"true"`
}
func (m *MySQL) SetDefaults() {
if m.Port == 0 {
m.Port = 3306
}
if m.PoolSize == 0 {
m.PoolSize = 10
}
if m.ConnMaxLifetime == 0 {
m.ConnMaxLifetime = envconfig.Duration(1 * time.Hour)
}
if m.Extra == "" {
values := url.Values{}
values.Set("charset", "utf8")
values.Set("parseTime", "true")
values.Set("interpolateParams", "true")
values.Set("autocommit", "true")
values.Set("loc", "Local")
m.Extra = values.Encode()
}
}
func (m *MySQL) URL() string {
password := m.Password
if password != "" {
password = ":" + password
}
return fmt.Sprintf("%s%s@tcp(%s:%d)", m.User, password, m.Host, m.Port)
}
func (m *MySQL) Connect() error {
m.SetDefaults()
db := m.Database.OpenDB(
&mysqlconnector.MysqlConnector{
Host: m.URL(),
Extra: m.Extra,
},
)
db.SetMaxOpenConns(m.PoolSize)
db.SetMaxIdleConns(m.PoolSize / 2)
db.SetConnMaxLifetime(time.Duration(m.ConnMaxLifetime))
m.DB = db
return nil
}
func (m *MySQL) Init() {
if m.DB == nil {
m.Do(m.Connect)
}
}
func (m *MySQL) Refresh() {
// TODO use pool to prevent close the connection immediately
if m.DB != nil {
if closer, ok := m.DB.SqlExecutor.(io.Closer); ok {
closer.Close()
}
}
m.Do(m.Connect)
}
func (m *MySQL) Get() *sqlx.DB {
if m.DB == nil {
panic(fmt.Errorf("get db before init"))
}
return m.DB
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/eden-framework/eden-framework.git
git@gitee.com:eden-framework/eden-framework.git
eden-framework
eden-framework
eden-framework
v2.0.2

搜索帮助