记一次应用cpu超高的性能优化.md

系统:normal-alpine3.9
服务框架:beego2.0
配置:6核3G

在一次服务性能压测过程中发现吞吐量很低,并且服务所在机器CPU占用消耗很大,直接拉满

一、首先在服务代码中引入pprof模块,设置对应路由和方法。

// 在router.go文件中添加如下代码
beego.Router("/debug/pprof", &controllers.ProfController{})

beego.Router("/debug/pprof/:app([\\w]+)", &controllers.ProfController{})

// 在controllers里面添加对应控制器代码

type ProfController struct {
    commCtrl.BaseController
}

func (c *ProfController) Get() {
   switch c.Ctx.Input.Param(":app") {
   default:
        pprof.Index(c.Ctx.ResponseWriter, c.Ctx.Request)
   case "":
       pprof.Index(c.Ctx.ResponseWriter, c.Ctx.Request)
   case "cmdline":
       pprof.Cmdline(c.Ctx.ResponseWriter, c.Ctx.Request)
   case "profile":
       pprof.Profile(c.Ctx.ResponseWriter, c.Ctx.Request)
   case "symbol":
       pprof.Symbol(c.Ctx.ResponseWriter, c.Ctx.Request)
   }
    c.Ctx.ResponseWriter.WriteHeader(200)
}

二、推送代码后打包成镜像发布。

    dockerfile 或 jenkinsfile都成

三、使用jemeter压测。

./jmeter -n -t test.jmx -l test.jtl

四、待压测过程进行稳定后,在本地执行命令抓取对应的资源占用情况

➜  pprof go tool pprof  http://10.101.17.220:80/debug/pprof/profile

Fetching profile over HTTP from http://10.101.17.220:80/debug/pprof/profile

Saved profile in /Users/lxcoscf/pprof/pprof.vcs.samples.cpu.010.pb.gz

File: vcs

Type: cpu

Time: Nov 17, 2021 at 8:08pm (CST)

Duration: 30.24s, Total samples = 1.27mins (251.63%)

Entering interactive mode (type "help" for commands, "o" for options)

(pprof)

可以直接在命令行使用tree、topN等命令查看对应等信息,如:

image.png

也可以exit退出命令行,然后在浏览器中查看对应等可视化图形,如:

➜  pprof go tool pprof -http=:8080 "/Users/lxcoscf/pprof/pprof.vcs.samples.cpu.0010.pb.gz"
image.png

可以发现从图中观察可以更直观的看到对应流程对CPU的占用情况,那么就可以有针对性的对服务进行优化;

测试案例图中可发现是redis的访问和json的序列化对CPU的消耗比较大,而redis方面,已经使用了资源池和pipeline,没有啥优化的空间了;而json的序列化方面,检查代码,发现有多次的访问redis并解析数据,然后对数据进行加工处理的过程,由于是一个重构项目,历史原型由PHP开发,而PHP对于数据类型不敏感,造成了本次重构过程中go里面的处理不变,影响了性能。

由于一些不可描述的原因,最终的解决方案就是用空间换CPU,减少序列化的次数。而做内存缓存又涉及到一些内容,有时间再总结一下这部分的处理。

你可能感兴趣的:(记一次应用cpu超高的性能优化.md)