mysql.go 1.75 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
package mysql

import (
	"fmt"
	"git.hilo.cn/hilo-common/mylogrus"
	"git.hilo.cn/hilo-common/resource/config"
	_ "github.com/go-sql-driver/mysql" //加载mysql驱动
	_ "github.com/joho/godotenv/autoload"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"net/url"
	"time"
)

var Db *gorm.DB

func init() {
	var err error
	mysqlConfigData := config.GetConfigMysql()
	options := "?charset=utf8mb4&parseTime=True&loc=Local&time_zone=" + url.QueryEscape("'+8:00'")
	dsn := "" + mysqlConfigData.MYSQL_USERNAME + ":" + mysqlConfigData.MYSQL_PASSWORD + "@(" + mysqlConfigData.MYSQL_HOST + ")/" + mysqlConfigData.MYSQL_DB + options

	sqlLogger := logger.Default.LogMode(logger.Info)
	if file := mylogrus.GetSqlLog(); file != nil {
		//sqlLogger = logger.New(log.New(file, "\r\n", log.Ldate|log.Lmicroseconds), logger.Config{
		sqlLogger = MyNew(log.New(file, "", log.Ldate|log.Lmicroseconds), logger.Config{
			SlowThreshold: 200 * time.Millisecond,
			LogLevel:      logger.Info,
			Colorful:      false,
		})
	}

	Db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: sqlLogger,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})
	if err != nil {
		log.Fatalf("mysql connect error %v", err)
	} else {
		log.Println("mysql connect success")
	}

	if Db.Error != nil {
		fmt.Printf("database error %v", Db.Error)
	}

	if d, err := Db.DB(); err == nil {
		d.SetConnMaxLifetime(time.Minute * 30) // 连接可复用的最大时间。
iamhujiebin's avatar
iamhujiebin committed
54 55
		d.SetMaxIdleConns(300)                 // 空闲连接数
		d.SetMaxOpenConns(300)                 // 最大连接数
56 57 58
		if err := d.Ping(); err != nil {
			fmt.Printf("database ping error %v", err)
		}
59 60
	}
}
chenweijian's avatar
chenweijian committed
61 62 63 64

func HasTable(tableName string) bool {
	return Db.Migrator().HasTable(tableName)
}