源码走读: fasthttp 为什么这么快?

前戏 今天我们聊聊 golang 的 web 框架, fasthttp 和 gin 到底谁更丝滑? fasthttp 简介 安装 go get -u github.com/valyala/fasthttp fasthttp 性能吊打 net/http 简而言之,fasthttp服务器的速度比net/http快多达 10 倍, 具体参数可以查看官网https://github.com/valyala/fasthttp fasthttp 使用方式与 net/http 有所差异 // using the given handler. func ListenAndServe(addr string, handler RequestHandler) error { s := &Server{ Handler: handler, } return s.ListenAndServe(addr) } type RequestHandler func(ctx *RequestCtx) 可以这样使用: type MyHandler struct { foobar string } // request handler in net/http style, i.e. method bound to MyHandler struct. func (h *MyHandler) HandleFastHTTP(ctx *fasthttp.RequestCtx) { // notice that we may access MyHandler properties here - see h.foobar. fmt.Fprintf(ctx, "Hello, world! Requested path is %q. Foobar is %q", ctx.Path(), h.foobar) } // pass bound struct method to fasthttp myHandler := &MyHandler{ foobar: "foobar", } fasthttp.ListenAndServe(":8080", myHandler.HandleFastHTTP) 在多个handler的时候需要这样使用: ...

十二月 27, 2024 · 5 分钟 · 1000 字 · zhu733756

性能提升秘籍:Golang对象池与复用技术,GC不再是瓶颈!

前戏 小白: 老花, 我今天想了解下 golang 的对象复用是干啥用的? 老花: 对象复用, 顾名思义, 就是把对象进行复用, 而不是每次都重新创建一个对象, 这样可以减少内存的开销, 提高性能, 减少 GC 的次数。 对象复用如何使用? golang的对象复用主要是要sync.Pool实现, 它是并发安全的对象池。 首先, 声明对象池, 需要提供一个对象的构造函数 New: var pool = sync.Pool{ New: func() interface{} { return new(MyType) // MyType 是你想要复用的对象类型 }, } 当从对象池中获取对象时,如果池中没有可用对象,会调用 New 函数创建一个新的对象。 使用 Get 方法从对象池中获取对象,使用 Put 方法将对象放回对象池。 obj := pool.Get().(*MyType) pool.Put(obj) 不过项目中, 我们都会简单地进行封装使用: var dataPool sync.Pool type UserData struct { Data []byte Key string } func GetUserData() *UserData { si := dataPool.Get() if si == nil { return &UserData{} } return si.(*UserData) } func PutUserData(si *UserData) { if si == nil { return } dataPool.Put(si) } 这样, 我们只需要使用GetUserData 和 PutUserData 就可以了。 ...

十二月 20, 2024 · 5 分钟 · 924 字 · zhu733756

性能翻倍!Golang开发者必读的pprof全攻略

前戏 小白: golang 有哪些性能提升的技巧? 能分享一下吗? 老花: 当然可以, 我们先看下如何分析我们的程序有什么性能问题吧! pprof 简介 pprof 是一个用于分析 Go 程序性能的工具,它提供了丰富的性能分析功能,包括 CPU、内存、goroutine、锁、网络、HTTP、GC 等等。 pprof 是 Go 语言自带的性能分析工具,可以帮助我们监控和分析程序的性能。 它有两个包: runtime/pprof:适用于所有类型的代码,特别是非 Web 应用程序。 net/http/pprof:对 runtime/pprof 的简单封装,适合 Web 应用程序使用,通过 HTTP 端口暴露性能数据。 pprof 监控内容 pprof 可以监控以下内容: allocs:内存分配情况的采样信息。 blocks:阻塞操作情况的采样信息。 cmdline:显示程序启动命令及参数。 goroutine:当前所有协程的堆栈信息。 heap:堆上内存使用情况的采样信息。 mutex:锁争用情况的采样信息。 profile:CPU 占用情况的采样信息。 threadcreate:系统线程创建情况的采样信息。 如何使用 pprof 对于 golang 代码, 我们可以使用下面这个办法来引入在线 pprof 分析工具: import ( _ "net/http/pprof" "net/http" ) func main() { go func() { http.ListenAndServe("localhost:6060", nil) }() // 程序主逻辑 } 这样,你就可以通过 go tool pprof http://localhost:6060/debug/pprof/heap访问堆栈, 其中heap可以换成allocs、goroutines、threadcreate等。 ...

十二月 19, 2024 · 4 分钟 · 712 字 · zhu733756