From dc051970d306223dc18b1f3ef40122df42cbb284 Mon Sep 17 00:00:00 2001 From: guzeng Date: Mon, 28 Feb 2022 22:57:15 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BB=8E=E5=BA=93=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- conn.go | 42 ++++++++++++++++++++++++++++++++++++++++++ db.go | 5 +++-- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/conn.go b/conn.go index a9db29b..d07a68d 100755 --- a/conn.go +++ b/conn.go @@ -15,6 +15,8 @@ import ( var DB *sql.DB +var SLAVER_DB *sql.DB + func Connect(DBHOST, DBUSER, DBPWD, DBNAME, DBPORT string, conns ...int) error { log.Println("database connectting...") @@ -55,6 +57,46 @@ func CloseConn() error { return DB.Close() } +func ConnectSlaver(DBHOST, DBUSER_SLAVER, DBPWD_SLAVER, DBNAME, DBPORT string, conns ...int) error { + + log.Println("database connectting with slaver...") + var dbConnErr error + if DBHOST != "" && DBUSER_SLAVER != "" && DBPWD_SLAVER != "" && DBPORT != "" { //&& DBNAME != "" + + for i := 0; i < 10; i++ { + SLAVER_DB, dbConnErr = sql.Open("mysql", DBUSER_SLAVER+":"+DBPWD_SLAVER+"@tcp("+DBHOST+":"+DBPORT+")/"+DBNAME+"?charset=utf8mb4") + if dbConnErr != nil { + log.Println("ERROR", "can not connect to Database, ", dbConnErr) + time.Sleep(time.Second * 5) + } else { + if len(conns) > 0 { + SLAVER_DB.SetMaxOpenConns(conns[0]) //用于设置最大打开的连接数,默认值为0表示不限制 + } else { + SLAVER_DB.SetMaxOpenConns(200) //默认值为0表示不限制 + } + if len(conns) > 1 { + SLAVER_DB.SetMaxIdleConns(conns[1]) //用于设置闲置的连接数 + } else { + SLAVER_DB.SetMaxIdleConns(50) + } + + SLAVER_DB.Ping() + + log.Println("database connected") + SLAVER_DB.SetConnMaxLifetime(time.Minute * 2) + break + } + } + } else { + return errors.New("db connection params errors") + } + return dbConnErr +} + +func CloseSlaverConn() error { + return SLAVER_DB.Close() +} + /** * 检测表名 */ diff --git a/db.go b/db.go index 6db2c22..a8fce76 100644 --- a/db.go +++ b/db.go @@ -355,9 +355,10 @@ func GetRow(dbName, table_name, alias string, titles string, join [][]string, wh var rows *sql.Rows var err error var queryNum int = 0 + for queryNum < 2 { //如发生错误,继续查询2次,防止数据库连接断开问题 - rows, err = DB.Query(sql_str, valueList...) + rows, err = SLAVER_DB.Query(sql_str, valueList...) if err == nil { break @@ -499,7 +500,7 @@ func FetchRows(dbName, table_name, alias string, titles string, join [][]string, var queryNum int = 0 for queryNum < 2 { //如发生错误,继续查询2次,防止数据库连接断开问题 - rows, err = DB.Query(sql_str, valueList...) + rows, err = SLAVER_DB.Query(sql_str, valueList...) if err == nil { break