作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢!
直接上代码:
import (
"github.com/valyala/bytebufferpool"
"github.com/valyala/fasthttp"
)
func FasthttpHandler(ctx *fasthttp.RequestCtx) {
buf := bytebufferpool.Get()
WritePageTemplate(buf, params) // 这里使用了 quick template 来输出 html
ctx.Response.Header.Add("Content-Encoding", "gzip")
fasthttp.WriteGzipLevel(ctx.Response.BodyWriter(), buf.Bytes(), fasthttp.CompressBestSpeed)
bytebufferpool.Put(buf)
}
我当前的服务,输出的 html 大约 1k 左右。
性能表现如下:
- 开启 gzip:
- Requests/sec: 16947.60
- Transfer/sec: 17.92MB
- 关闭 gzip:
- Requests/sec: 33269.73 (性能提升 1.96 倍)
- Transfer/sec: 74.59MB (流量增加 4.16 倍)
开启 gzip 对性能的影响还是比较明显的,估计是输出的内容越长,收益越大。
就看在 qps 和带宽两者之间更关注什么指标。