duanjiwu0324 2014-12-20 16:47
浏览 36
已采纳

MGO和长期运行的Web服务-恢复

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()
    ds.OpenSession()
    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?

Thanks!

  • 写回答

1条回答 默认 最新

  • 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?