写点什么

盘点 golang 中的开发神器

用户头像
捉虫大师
关注
发布于: 2021 年 05 月 28 日

在 Java 中,我们用 Junit 做单元测试,用 JMH 做性能基准测试(benchmark),用 async-profiler 剖析 cpu 性能,用 jstack、jmap、arthas 等来排查问题。作为一名比较新的编程语言,golang 的这些工具是否更加好用呢?

单元测试

Java 的单元测试需要使用第三方库,一般是 Junit,配置起来比较复杂。在使用了 golang 之后发现 golang 自带的单元测试真的非常简单。如果我们有一个 cal.go 文件,那么其对应的单元测试文件为 cal_test.go,其中的方法命名必须为 TestXxx,这种按照命名进行单元测试的方式简单有效,也正是通常所说的“约定大于配置”。来看一个简单的例子:

package unit
func add(a int, b int) int {   return a + b}
func sub(a int, b int) int {   return a - b}
复制代码


package unit
import (    "github.com/stretchr/testify/assert"    "testing")
func TestAdd(t *testing.T) {    assert.Equal(t, 10, add(5, 5))}
func TestSub(t *testing.T) {    assert.Equal(t, 0, sub(5, 5))}
复制代码

执行单元测试只需要运行(更多用法参考 go help test)

go test --cover cal_test.go cal.go -v
复制代码


benchmark

和单元测试类似,golang 的 benchmark 也是开箱即用。在 cal_test.go 基础上增加一个 BenchmarkAdd 方法

package unit
import (   "github.com/stretchr/testify/assert"   "testing")
func TestAdd(t *testing.T) {   assert.Equal(t, 10, add(5, 5))}
func TestSub(t *testing.T) {   assert.Equal(t, 0, sub(5, 5))}
func BenchmarkAdd(b *testing.B) {   for i:= 0; i < b.N; i++ {      add(5, 5)   }}
复制代码

执行即可(更多用法参考 go help test)

go test -bench=. -cpu=4 -count=3
复制代码


pprof

pprof 是 golang 自带的可以用来做 cpu、内存、锁分析的工具,非常类似 java 的 async-profiler。pprof 的使用非常简单,只需要在代码中引入 net/http/pprof 包,然后监听一个端口即可。一个简单的例子如下:

package main
import (    "fmt"    "log"    "net/http"    "time"    _ "net/http/pprof")
func main() {    go func() {        //example: visit http://127.0.0.1:6060/debug/pprof in browser.        err := http.ListenAndServe("0.0.0.0:6060", nil)        if err != nil {            fmt.Println("failed to start pprof goroutine:", err)        }    }()
    http.HandleFunc("/", handler)    log.Fatal(http.ListenAndServe("localhost:8000", nil))}
func handler(w http.ResponseWriter, r *http.Request) {    time.Sleep(1 * time.Second)    eat()    time := time.Now().Unix() * 2 + 1000000    fmt.Fprintf(w, "URL.Path = %q; time = %d\n", r.URL.Path, time)}
func eat() {    loop := 10000000000    for i := 0; i < loop; i++ {        // do nothing    }}
复制代码

在命令行中输入

go tool pprof http://127.0.0.1:6060/debug/pprof/profile
复制代码

同时不停的请求,让 pprof 能采集到数据,这里我的请求是

curl http://127.0.0.1:8000/hello
复制代码

等待 30 秒后,采集结束会显示采集文件的地址

Saved profile in /Users/roshi/pprof/pprof.samples.cpu.003.pb.gz
复制代码

此时可以使用 top 等命令直接查看 cpu 消耗过高的函数,更多命令可以使用 help 查看。

或者把文件下载下来用可视化的界面来分析,可以使用

go tool pprof -http=":8080" /User/roshi/pprof/pprof.samples.cpu.003.pb.gz
复制代码

来开启一个可视化的页面,查看,如果报错需要安装 graphviz,安装文档在这里可以查找:https://graphviz.gitlab.io/download/

访问 http://localhost:8080/ui/ 可以看到下图,其中面积最大的块表示消耗 cpu 最多

这里有一篇文章对 pprof 介绍的很仔细,可以参考:https://blog.wolfogre.com/posts/go-ppof-practice/

dlv

pprof 很好用,但有一个缺点是必须事先在代码中开启,如果线上出问题且没有开启 pprof,可能就需要类似 jstack、jmap、arthas 等这类工具来排查。这里推荐一个最近使用过非常好用的 golang 问题排查利器——dlv,项目地址见

https://github.com/go-delve/delve

它很有用的一个功能是 attach,可以 attach 到正在运行的 golang 程序,查看 goroutine。这点可以很好的排查线上问题。各个平台的安装在 github 上写的很清楚,需要说明的是安装 dlv 的 golang 版本和要排查进程的 golang 版本需要保持一致。先写一个测试程序,起两个 goroutine,一个运行,一个阻塞

package main
import (   "fmt"   "sync")
func main()  {   go count()   go wait()   wait()}
func count()  {   count := 0   for {      count = count + 1      if count % 1000000000 == 0 {         fmt.Println("I'm a running routine")      }   }}
func wait()  {   wg := sync.WaitGroup{}   wg.Add(1)   wg.Wait()}
复制代码

运行起来,然后使用 dlv 进行 attach,如下图(具体命令可以 attach 后使用 help 查看)

这样很方便地看到了各个 goroutine 在干啥

写在最后

作为一门比较新的编程语言,golang 对现有语言取其精华,自带必要的工具,进一步降低门槛,对新手学习来说非常友好。


关于作者:专注后端的中间件开发,公众号"捉虫大师"作者,关注我,给你最纯粹的技术干货


发布于: 2021 年 05 月 28 日阅读数: 56
用户头像

捉虫大师

关注

还未添加个人签名 2018.09.19 加入

欢迎关注我的公众号“捉虫大师”

评论

发布
暂无评论
盘点golang中的开发神器