func MInit(uri, dbName, k string) error { DB_NAME = dbName n := time.Second var e error var m_conn *mgo.Session = mcMap[k] for { if session, err := mgo.Dial(uri); err != nil { e = err } else { m_conn = session if err := m_conn.Ping(); err != nil { e = err } else { break } } fmt.Printf("fail to connect mysql,err:%v,uri:%s,try to reconnect in %d second\n", e, uri, n/1000000000) time.Sleep(n) n = n * 2 //最大重连间隔时长:10分钟 if n > 600*time.Second { n = 600 * time.Second } } mcMap[k] = m_conn return nil }
func GetMConn(k string) *mgo.Session { var m_conn *mgo.Session = getMConn(k) var n = time.Second for { if err := m_conn.Ping(); err != nil { fmt.Printf("mongodb断开连接,%d秒后开始重连", n/time.Second) m_conn.Refresh() } else { if n/time.Second > 1 { fmt.Printf("重连成功") } break } fmt.Println("正在尝试重连") time.Sleep(n) n = n * 2 //最大重连间隔时长:10分钟 if n > 600*time.Second { n = 600 * time.Second } } return m_conn }