2024年10月

写好的程序放到linux服务器,隔几天上服务器一看,内存直接爆了。

本地buid程序测试,内存也是一下子升到几个G,开发的时候一直用的是goland,没发现这个问题。

1、把time.After改成time.NewTimer,发现没效果

2、 用 net/http/pprof 分析,刚开始觉得是太多http请求引起的 http client 内存泄漏,网上研究了好多资料,对 http client 参数也是做各种修改,搞了一天,无果。

3、 golang项目中的issues搜索 "http client memory leak",无意间看到 https://github.com/golang/go/issues/63276, 把 go build -race 中的 -race 删除,内存不飙升了,问题解决。

4、再去搜索 "go build -race" 就看到 https://go.dev/doc/articles/race_detector 这篇文章,最后面有说生产环境使用 go build -race 构建可能会让内存无限增长。

1、 通过 "cat /proc/sys/fs/nr_open" 查看系统限制,ulimit设置不能超过这个限制,通过"ulimit -n"查看当前限制
cat /proc/sys/fs/nr_open
ulimit -n
2、 通过 "ulimit -n 1000000"修改为100万
ulimit -n 1000000
3、 永久生效
echo 'root soft nofile 1000000' >> /etc/security/limits.conf
echo 'root hard nofile 1000000' >> /etc/security/limits.conf
echo '* soft nofile 1000000' >> /etc/security/limits.conf
echo '* hard nofile 1000000' >> /etc/security/limits.conf