2014-12-20 16:47 阅读 31


I've written a REST web service that uses mongo as the backend data store. I was wondering at this stage (before deployment), what the best practices were, considering a service that essentially runs forever(ish).

Currently, I'm following this type of pattern:

// database.go

type DataStore struct {
  mongoSession  *mgo.Session

func (d *DataStore) OpenSession () {
   ... // read setup from environment

   mongoSession, err = mgo.Dial(mongoURI)
   if err != nil {}

func (d *DataStore) CloseSession() {...}

func (d *DataStore) Find (...) (results...) {
    s := d.mongoSession.Copy()
    defer s.Close()

    // do stuff, return results

In main.go:

func main() {
    ds := NewDataStore()
    defer ds.CloseSession()

    // Web Service Routes..
    ws.Handle("/find/{abc}", doFindFunc)

My question is - what's the recommended practice for recovery from session that has timed out, lost connection (the mongo service provider I'm using is remote, so I assume that this will happen), so on any particular web service call, the database session may no longer work? How do people handle these cases to detect that the session is no longer valid and a "fresh" one should be established?


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanhan7001 duanhan7001 2014-12-27 10:32

    what you may want is to do the session .Copy() for each incoming HTTP request (with deffered .Close()), copy again from the new session in your handlers if ever needed..

    connections and reconnections are managed by mgo, you can stop and restart MongoDB while making an HTTP request to your web service to see how its affected.

    if there's a db connection problem while handling an HTTP request, a db operation will eventually timeout (timeout can be configured by using DialWithTimeout instead of the regular Dial, so you can respond with a 5xx HTTP error code in such case.

    点赞 评论 复制链接分享