This commit is contained in:
huangsimin 2018-12-10 14:40:38 +08:00
parent 5f27051688
commit fc789d2322

View File

@ -18,9 +18,8 @@ type LogDB struct {
Port string `yaml:"port"`
User string `yaml:"user"`
hostid int
driver *sql.DB
errorcount int
hostid int
driver *sql.DB
}
// NewLogDB 创建一个logdb的配置
@ -41,37 +40,52 @@ func NewLogDB(filename string) *LogDB {
}
// Ping 是否Ping通数据库
func (logdb *LogDB) Ping() error {
return logdb.driver.Ping()
}
// Connect 重连
func (logdb *LogDB) Connect() {
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++ {
logdb.errorcount++
if logdb.errorcount >= hostlen*2 {
panic(err)
}
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", logdb.User, logdb.Password, logdb.Hosts[logdb.hostid], logdb.Port, logdb.DB))
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?timeout=1s&charset=%s", logdb.User, logdb.Password, logdb.Hosts[i], logdb.Port, logdb.DB, logdb.Charset))
if err != nil {
log.Println(err, logdb.Hosts[logdb.hostid], " is connect fail")
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
break
result = true
}
}
}()
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", logdb.User, logdb.Password, logdb.Hosts[logdb.hostid], logdb.Port, logdb.DB))
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=1s&charset=%s", logdb.User, logdb.Password, logdb.Hosts[logdb.hostid], logdb.Port, logdb.DB, logdb.Charset))
if err != nil {
panic(err)
}
db.Ping()
if logdb.driver != nil {
logdb.driver.Close()
}
logdb.driver = db
log.Println("connect is", logdb.Ping(), logdb)
}