func mainloop(db *sql.DB) {
type pushTask struct {
TaskId string
Uri string
}
stmt, err := db.Prepare("INSERT INTO ErrPushCache(TaskId, Uri) VALUES(?, ?)")
if err != nil {
log.Fatal("db.Prepare Failed ", err)
}
var (
mysqlOk bool = true
task pushTask
)
for {
task.TaskId = RandStringRunes(8)
task.Uri = RandStringRunes(16)
res, err := stmt.Exec(task.TaskId, task.Uri)
if err != nil {
if err == driver.ErrBadConn {
if mysqlOk {
log.Print("Connection with mysql seems down, %s", err.Error())
mysqlOk = false
os.Exit(1)
}
} else {
log.Print("Exec failed ", err)
}
time.Sleep(2 * time.Second)
continue
}
if !mysqlOk {
log.Print("Connection with mysql is ok now")
mysqlOk = true
}
lastId, err := res.LastInsertId()
if err != nil {
log.Print("LastInsertId failed ", err)
}
rowCnt, err := res.RowsAffected()
if err != nil {
log.Print("RowsAffected failed ", err)
}
log.Printf("ID = %d, affected = %d\n", lastId, rowCnt)
time.Sleep(20 * time.Second)
}
}
在mainloop函数中,如果mysql和客户端的连接断开,stmt.Exec就会失败,会返回一个错误,我如何区分连接错误和其他错误。(err == driver.ErrBadConn总是false)。
如果连接中断,则日志为:
2016/01/29 17:21:31 Exec 拨号 tcp 192.168.1.61:3306 失败:getsockopt:连接被拒绝 2016/01/29 17:21:33 Exec 拨号 tcp 192.168.1.61:3016 连接被拒绝失败01/29 17:21:35 Exec 拨号 tcp 192.168.1.61:3306 失败:getsockopt:连接被拒绝 2016/01/29 17:21:37 Exec 拨号 tcp 192.168.1.61:3306 失败:getsockopt/getsockopt/连接被拒绝29 17:21:39 Exec 拨号 tcp 192.168.1.61:3306 失败:getsockopt:连接被拒绝
子衿沉夜
神不在的星期二
相关分类