首页 > 其他 > 详细

golang 模拟内存溢出

时间:2021-05-02 16:49:33      阅读:29      评论:0      收藏:0      [点我收藏+]

package main

import (
"fmt"
"github.com/gin-gonic/gin"
"math/rand"
"net/http"
_ "net/http/pprof"
"runtime"
"time"
)

var m = map[int64]int64{}
var r = rand.New(rand.NewSource(time.Now().Unix()))

func main() {
go http.ListenAndServe(":6060", nil)
go func() {
for {
var _ string
}
}()

go func() {
	for {
		time.Sleep(10 * time.Millisecond)
		key := r.Int63()
		m[key] = key
	}
}()
for {
	time.Sleep(1 * time.Second)
	fmt.Println(runtime.NumGoroutine())
}

}

func initHttp() {
router := gin.Default()
router.Use(gin.Recovery())
router.Use(func(context *gin.Context) {
fmt.Println("第一个前")
context.Next()
fmt.Println("第一个后")
})
router.Use(func(context *gin.Context) {
fmt.Println("第二个前")
context.Next()
fmt.Println("第二个后")
})
router.GET("/", func(context *gin.Context) {
fmt.Println("处理器")
fmt.Println("handler")
m := map[string]string{};
m["aaa"] = "bbb";
context.JSON(http.StatusOK, m);
})
go router.Run(":8080")
}

上面的代码会内存溢出
步骤一
访问http://127.0.0.1:6060/debug/pprof/heap?debug=1,会发现内存持续增加。
步骤二
访问go tool pprof http://127.0.0.1:6060/debug/pprof/heap,然后执行top命令,可以看到占用内存最大的协程,然后执行list命令可以看到是哪一行占用内存过高。
技术分享图片

golang 模拟内存溢出

原文:https://www.cnblogs.com/l15527952185/p/14725758.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!