/usr/local/go
,推荐使用Go Modules管理依赖(go mod init
)。/etc/profile
或~/.bashrc
,添加:export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
export GOPROXY=https://goproxy.cn,direct # 国内加速
执行source /etc/profile
使生效。GOGC
环境变量控制GC触发频率(默认100),可设为50-200,降低GC开销。export GOGC=75
func main() {
ballast := make([]byte, 10*1024*1024*1024)
runtime.KeepAlive(ballast)
}
sync.Pool
复用对象,减少内存分配。easyjson
替代encoding/json
提升JSON序列化性能。goroutine
和channel
,控制并发数量。/etc/security/limits.conf
):* soft nofile 65536
* hard nofile 65536
/etc/sysctl.conf
):net.core.somaxconn=65535
net.ipv4.tcp_tw_reuse=1
net.ipv4.tcp_fin_timeout=30
执行sysctl -p
生效。pprof
分析CPU/内存:go tool pprof http://localhost:6060/debug/pprof/profile
FlameGraph
生成火焰图定位瓶颈。zap
等高效日志库。使用-ldflags "-s -w"
减少二进制体积,提升启动速度:
go build -ldflags "-s -w" -o myapp
启用HTTP/2,使用fasthttp
等高性能库,调整TCP参数(如缓冲区大小、禁用Nagle算法)。
参考来源: