douxie1957 2014-08-29 14:23
浏览 14
已采纳

最佳实践开放数据库

Note: I am not sure if this is the most accurate title for this post, if not, please advise on a better one.

Currently I am creating a server where I have a couple of handlers (using goji). After receiving a request, I want to interact with a MongoDB database I have (using mgo). My question is:

I am assuming doing this kind of stuff every time I am handling a request is expensive:

uri := os.Getenv("MONGOHQ_URL")

if uri == "" {

    panic("no DB connection string provided")
}

session, err := mgo.Dial(uri)

So, would it be better for me to have a global var that I can access from inside the handlers? So I would go with something like this:

var session *mgo.Session

func main() {

    session = setupDB()
    defer session.Close()

    goji.Get("/user", getUser)
    goji.Serve()
}

func getUser(c web.C, w http.ResponseWriter, r *http.Request) {
// Use the session var here
}

My question is related to what would be the best practise here? Opening the DB every time a request comes in, or keep it open for the entire duration of the application.

  • 写回答

1条回答 默认 最新

  • doufei2007 2014-08-29 14:55
    关注

    What about wraping your handler in a Controller struct like this: (http://play.golang.org/p/NK6GO_lqgk)

    package main
    
    import (
        "fmt"
        "log"
        "net/http"
        "os"
    
        "github.com/zenazn/goji"
        "github.com/zenazn/goji/web"
    )
    
    type Controller struct {
        session *Session
    }
    
    func NewController() (*Controller, error) {
        if uri := os.Getenv("MONGOHQ_URL"); uri == "" {
            return nil, fmt.Errorf("no DB connection string provided")
        }
        session, err := mgo.Dial(uri)
        if err != nil {
            return nil, err
        }
        return &Controller{
            session: session,
        }, nil
    }
    
    func (c *Controller) getUser(c web.C, w http.ResponseWriter, r *http.Request) {
        // Use the session var here
    }
    
    func main() {
        ctl, err := NewController()
        if err != nil {
            log.Fatal(err)
        }
        defer ctl.session.Close()
    
        goji.Get("/user", ctl.getUser)
        goji.Serve()
    }
    

    This way, you can embed your session in your handler and add any other data that you might need.

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

报告相同问题?

悬赏问题

  • ¥15 在TensorFlow框架下使用神经网络报错(语言-python)
  • ¥30 codelite全屏时file、setting那一行消失了
  • ¥15 gazebo-rviz教程
  • ¥15 付费求做一个自助抢单插件
  • ¥15 bat批处理,关于数据复制问题
  • ¥50 同步两个不同结果的array中某些属性
  • ¥15 悬赏15远程操控解决问题
  • ¥15 CST复制的模型无法单独修改参数?
  • ¥15 前端页面想做个定时任务,但是使用requestAnimationFrame,setinterval和settimeout都不行
  • ¥15 根据以下文字信息,做EA模型图