MongoDB + Revel + mgo + revmgo 开发的网站如何实现自动重连

小弟最近用MongoDB + Revel + mgo + revmgo 开发了一个网站,MongoDB和Server是分开的两个服务器。但有个问题就是如果MongoDb因为某种原因断开连接(这种情况很明显不可避免),哪怕只断开有一秒钟,Server那边网站就会出现数据库无法连接的错误。 不知道有没有哪位大神能有好点的解决方案?


ffdysd 于 2013-12-26 12:09 修改
3 回复


#1ffdysd

ffdysd • 2013-12-26 15:41

我用最新版的mgo就没有这个问题了! 刚看了源码,应该是最新版的mgo 在Close() session的时候把 变量session 赋值为nil 了,然后每次调用controller 的时候都会重新连了。

  1. // Connect to mgo if we haven't already and return a copy/new/clone of the session
  2. func (c *MongoController) Begin() revel.Result {
  3. // We may not be connected yet if revel was started before Mongo DB or
  4. // Mongo DB was restarted
  5. ***if Session == nil {***
  6. var err error
  7. Session, err = mgo.Dial(Dial)
  8. if err != nil {
  9. // Extend the error description to include that this is a Mongo Error
  10. err = fmt.Errorf("Could not connect to Mongo DB. Error: %s", err)
  11. return c.RenderError(err)
  12. } else {
  13. setDuplMethod()
  14. }
  15. }
  16. // Calls Clone(), Copy() or New() depending on the configuration
  17. c.MongoSession = mgoSessionDupl()
  18. return nil
  19. }
  20. // Close the controller session if we have an active one.
  21. func (c *MongoController) End() revel.Result {
  22. // This is necessary since End() will be called no matter what
  23. // (revel.FINALLY) so it may not be connected in which case MongoSession
  24. // were a nil pointer and panic
  25. if c.MongoSession != nil {
  26. c.MongoSession.Close()
  27. }
  28. return nil
  29. }
#2gihnius

gihnius • 2013-12-26 18:42

我暂时是这么解决的, 不算完全解决吧

  1. results, err := Query.....
  2. if err != nil {
  3. CheckMongoErr()
  4. }
  5. func CheckMongoErr() {
  6. err := Mongo.Session.Ping()
  7. if err != nil {
  8. fmt.Println("Lost connection to db!")
  9. Mongo.Session.Refresh()
  10. err = Mongo.Session.Ping()
  11. if err == nil {
  12. fmt.Println("Reconnect to db successful.")
  13. }
  14. }
  15. }

就是每个 query 出错的话去 refresh 一下 session.

#3ffdysd

ffdysd • 2013-12-26 22:01

回复:gihnius 最新版的mgo 已经没有这个问题了。

Tagged: ,

Comments are closed.