92 lines
1.9 KiB
Go
92 lines
1.9 KiB
Go
package logdb
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"log"
|
|
|
|
yaml "gopkg.in/yaml.v2"
|
|
)
|
|
|
|
// LogDB 属性结构
|
|
type LogDB struct {
|
|
Charset string `yaml:"charset"`
|
|
DB string `yaml:"db"`
|
|
Hosts []string `yaml:"hosts"`
|
|
Password string `yaml:"password"`
|
|
Port string `yaml:"port"`
|
|
User string `yaml:"user"`
|
|
|
|
hostid int
|
|
driver *sql.DB
|
|
}
|
|
|
|
// NewLogDB 创建一个logdb的配置
|
|
func NewLogDB(filename string) *LogDB {
|
|
logdb := LogDB{}
|
|
data, err := ioutil.ReadFile(filename)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
err = yaml.Unmarshal(data, &logdb)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
logdb.hostid = 0
|
|
|
|
logdb.Connect()
|
|
return &logdb
|
|
}
|
|
|
|
// Ping 是否Ping通数据库
|
|
func (logdb *LogDB) Ping() (result bool) {
|
|
defer func() {
|
|
if err := recover(); err != nil {
|
|
result = false
|
|
|
|
log.Println(err, logdb.Hosts[logdb.hostid], " is unconnect ")
|
|
hostlen := len(logdb.Hosts)
|
|
for i := 0; i < hostlen; i++ {
|
|
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?timeout=15s&charset=%s", logdb.User, logdb.Password, logdb.Hosts[i], logdb.Port, logdb.DB, logdb.Charset))
|
|
if err != nil {
|
|
log.Println(err, logdb.Hosts[i], " is connect fail")
|
|
continue
|
|
}
|
|
|
|
if err := db.Ping(); err != nil {
|
|
log.Println(err, logdb.Hosts[i], " is connect fail")
|
|
continue
|
|
}
|
|
|
|
logdb.driver = db
|
|
logdb.hostid = i
|
|
result = true
|
|
}
|
|
}
|
|
}()
|
|
|
|
if err := logdb.driver.Ping(); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
// Connect 重连
|
|
func (logdb *LogDB) Connect() {
|
|
logdb.hostid++
|
|
if logdb.hostid >= len(logdb.Hosts) {
|
|
logdb.hostid = 0
|
|
}
|
|
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?timeout=15s&charset=%s", logdb.User, logdb.Password, logdb.Hosts[logdb.hostid], logdb.Port, logdb.DB, logdb.Charset))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if logdb.driver != nil {
|
|
logdb.driver.Close()
|
|
}
|
|
logdb.driver = db
|
|
log.Println("connect is", logdb.Ping(), logdb)
|
|
}
|