Go http标准库中的内存泄漏?

Mar*_*ark 14 memory-leaks memory-management http standard-library go

有一个Go二进制实现一个http服务器:

package main

import (
    "net/http"
)

func main() {
    http.ListenAndServe(":8080", nil)
}
Run Code Online (Sandbox Code Playgroud)

它将以约850 kb左右的内存开始.通过您的网络浏览器发送一些请求.观察它迅速上升到1 MB.如果你等待,你会发现它永远不会消失.现在用Apache Bench(使用下面的脚本)敲击它,看看你的内存使用量不断增加.一段时间后,最终将达到8.2 MB左右的高原.

编辑:它似乎没有停在8.2,而是显着减慢.它目前在9.2并且还在上升.

简而言之,为什么会发生这种情况?我用过这个shell脚本:

while [ true ]
do
    ab -n 1000 -c 100 http://127.0.0.1:8080/
    sleep 1
end
Run Code Online (Sandbox Code Playgroud)

在尝试深入研究时,我试图调整设置.我试过关闭使用r.Close = true以防止Keep-Alive.似乎没什么用.

我最初在尝试确定我正在编写的程序中是否存在内存泄漏时发现了这一点.它有很多http处理程序和I/O调用.检查后我已经关闭了所有数据库连接,我一直看到它的内存使用率上升.我的计划到了433 MB左右的高原.

这是Goenv的输出:

GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/mark/Documents/Programming/Go"
GORACE=""
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
TERM="dumb"
CC="clang"
GOGCCFLAGS="-g -O2 -fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fno-common"
CXX="clang++"
CGO_ENABLED="1"
Run Code Online (Sandbox Code Playgroud)

az_*_*az_ 18

pprof你在评论中提供的堆,看起来你正在通过gorilla/sessionsgorilla/context(几乎400MB)泄漏内存.

请参阅此ML主题:https://groups.google.com/forum/#! msg/gorilla-web/clJfCzenuWY/ N_Xj9-5Lk6wJ和此GH问题:https://github.com/gorilla/sessions/issues/ 15

这是一个泄漏速度非常快的版本:

package main

import (
    "fmt"
    // "github.com/gorilla/context"
    "github.com/gorilla/sessions"
    "net/http"
)

var (
    cookieStore = sessions.NewCookieStore([]byte("cookie-secret"))
)

func main() {
    http.HandleFunc("/", defaultHandler)
    http.ListenAndServe(":8080", nil)
}

func defaultHandler(w http.ResponseWriter, r *http.Request) {
    cookieStore.Get(r, "leak-test")
    fmt.Fprint(w, "Hi there")
}
Run Code Online (Sandbox Code Playgroud)

这是一个清理并具有相对静态的RSS:

package main

import (
    "fmt"
    "github.com/gorilla/context"
    "github.com/gorilla/sessions"
    "net/http"
)

var (
    cookieStore = sessions.NewCookieStore([]byte("cookie-secret"))
)

func main() {
    http.HandleFunc("/", defaultHandler)
    http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux))
}

func defaultHandler(w http.ResponseWriter, r *http.Request) {
    cookieStore.Get(r, "leak-test")
    fmt.Fprint(w, "Hi there")
}
Run Code Online (Sandbox Code Playgroud)

  • `gorilla/context`在内部将数据存储在`map [request] ...`(和`sessions`使用`context`)中,因此处理程序需要在请求终止后从地图中删除请求.看起来像`gorilla/sessions`被设计用于`gorilla/mux`路由器(它自动清除地图). (5认同)