mgo go服务器中打开的文件太多了

时间:2017-11-08 12:35:21

标签: mongodb ubuntu go mgo

我在日志中收到这些错误:

  

接受错误:接受tcp [::]:80:accept4:打开的文件太多;

用于ubuntu上的mongodb服务器,使用mgo编写。它们在运行了大约一天后才开始出现。

代码:

package main

import (
    "encoding/json"
    "io"
    "net/http"

    "gopkg.in/mgo.v2/bson"
)

var (
    Database *mgo.Database
)

func hello(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "hello")
}

func setTile(w http.ResponseWriter, r *http.Request) {
    var requestJSON map[string]interface{}
    err := json.NewDecoder(r.Body).Decode(&requestJSON)
    if err != nil {
        http.Error(w, err.Error(), 400)
        return
    }

    collection := Database.C("tiles")

    if requestJSON["tileId"] != nil {
        query := bson.M{"tileId": requestJSON["tileId"]}
        collection.RemoveAll(query)
        collection.Insert(requestJSON)

        w.WriteHeader(200)
        w.Header().Set("Content-Type", "application/json")
        js, _ := json.Marshal(map[string]string{"result": "ok"})
        w.Write(js)
    } else {
        w.WriteHeader(200)
        w.Header().Set("Content-Type", "application/json")
        w.Write(js)
    }
}

func getTile(w http.ResponseWriter, r *http.Request) {
    var requestJSON map[string]interface{}
    err := json.NewDecoder(r.Body).Decode(&requestJSON)
    if err != nil {
        http.Error(w, err.Error(), 400)
        return
    }

    collection := Database.C("tiles")

    var result []map[string]interface{}

    if requestJSON["tileId"] != nil {
        query := bson.M{"tileId": requestJSON["tileId"]}
        collection.Find(query).All(&result)
    }

    if len(result) > 0 {
        w.WriteHeader(200)
        w.Header().Set("Content-Type", "application/json")
        js, _ := json.Marshal(result[0])
        w.Write(js)
    } else {
        w.WriteHeader(200)
        w.Header().Set("Content-Type", "application/json")
        js, _ := json.Marshal(map[string]string{"result": "tile id not found"})
        w.Write(js)
    }
}

func main() {
    session, _ := mgo.Dial("localhost")
    Database = session.DB("mapdb")

    mux := http.NewServeMux()
    mux.HandleFunc("/", hello)
    mux.HandleFunc("/setTile", setTile)
    mux.HandleFunc("/getTile", getTile)
    http.ListenAndServe(":80", mux)
}

那里有什么东西需要关闭吗?或者它在某种程度上是错误的?

似乎有很多地方可以设置打开的文件限制,所以我不知道如何找出实际的限制。但似乎无论如何增加限制都不是问题,肯定会在每个请求上打开一些东西而不是关闭。

2 个答案:

答案 0 :(得分:3)

这不是你在Go中存储和使用MongoDB连接的方式。

您必须存储mgo.Session,而不是mgo.Database个实例。每当您需要与MongoDB进行交互时,您都会获得会话的副本或克隆(例如,使用Session.Copy()Session.Clone()),并在不需要时关闭它(最好使用它) defer声明。这将确保您不会泄漏连接。

你也虔诚省略检查错误,请不要这样做。无论返回error,都要检查并正确操作(至少可以打印/记录它)。

基本上你需要做的是这样的事情:

var session *mgo.Session

func init() {
    var err error
    if session, err = mgo.Dial("localhost"); err != nil {
        log.Fatal(err)
    }
}

func someHandler(w http.ResponseWriter, r *http.Request) {
    sess := session.Copy()
    defer sess.Close() // Must close!

    c := sess.DB("mapdb").C("tiles")
    // Do something with the collection, e.g.
    var tile bson.M
    if err := c.FindId("someTileID").One(&result); err != nil {
        // Tile does not exist, send back error, e.g.:
        log.Printf("Tile with ID not found: %v, err: %v", "someTileID", err)
        http.NotFound(w, r)
        return
    }
    // Do something with tile
}

参见相关问题:

mgo - query performance seems consistently slow (500-650ms)

Concurrency in gopkg.in/mgo.v2 (Mongo, Go)

答案 1 :(得分:0)

您不见了:

defer r.Body.Close()

确保在return语句之前使用它。