go1.20.5.linux-amd64.tar.gz),解压至/usr/local目录:wget https://golang.org/dl/go1.20.5.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.20.5.linux-amd64.tar.gz
yum安装(版本较旧,不推荐):sudo yum install -y epel-release
sudo yum install -y golang
~/.bashrc(或~/.bash_profile、~/.zshrc,根据shell类型选择),添加以下内容:export GOROOT=/usr/local/go # Golang安装路径
export GOPATH=$HOME/go # 工作空间路径(用于存放项目及依赖)
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin # 将Golang命令加入系统PATH
export GO111MODULE=on # 启用Go Modules(推荐,替代传统GOPATH模式)
source ~/.bashrc(或对应配置文件),验证安装:go version # 应输出Golang版本信息(如go1.20.5 linux/amd64)
GOPROXY指向国内镜像(如中科大镜像):echo 'export GOPROXY=https://goproxy.cn,direct' >> ~/.bashrc
source ~/.bashrc
这样go get命令会优先从国内镜像下载依赖,避免网络延迟。GOGC控制GC触发频率(默认100%,即内存翻倍时触发)。可根据应用内存使用调整:export GOGC=75 # 内存增长75%时触发GC(降低GC频率,适合内存敏感场景)
# 或 export GOGC=50 # 更频繁触发GC(减少内存占用,适合高并发场景)
func main() {
ballast := make([]byte, 10*1024*1024*1024) // 10GB球囊内存
runtime.KeepAlive(ballast) // 防止编译器优化掉该变量
}
sync.Pool复用对象(如数据库连接、缓冲区),避免频繁new/make:var bufferPool = sync.Pool{
New: func() interface{} { return make([]byte, 1024) },
}
buf := bufferPool.Get().([]byte)
defer bufferPool.Put(buf)
goroutine+channel,避免创建过多Goroutine(可通过信号量限制并发数):sem := make(chan struct{}, 100) // 限制并发数为100
for _, task := range tasks {
sem <- struct{}{}
go func(t Task) {
defer func() { <-sem }()
// 处理任务
}(task)
}
easyjson替代原生encoding/json(需提前安装:go install github.com/mailru/easyjson@latest),生成更高效的序列化/反序列化代码:easyjson -all user.go # 为用户结构体生成优化方法
import _ "net/http/pprof"
func main() {
go func() { http.ListenAndServe("localhost:6060", nil) }() // 启动pprof服务
// 应用代码
}
通过go tool pprof http://localhost:6060/debug/pprof/profile(CPU分析)或http://localhost:6060/debug/pprof/heap(内存分析)查看热点函数。FlameGraph工具生成可视化火焰图,更直观定位性能瓶颈:go tool pprof -http=:8080 http://localhost:6060/debug/pprof/profile
-ldflags "-s -w"移除调试信息和符号表,减小二进制文件大小(提升启动速度):go build -ldflags="-s -w" -o myapp
/etc/security/limits.conf,添加以下内容(允许单个进程打开最多65536个文件):* soft nofile 65536
* hard nofile 65536
重新登录后生效,避免高并发场景下出现“too many open files”错误。/etc/sysctl.conf,添加以下参数(提升网络性能):net.core.somaxconn = 65535 # 监听队列最大长度
net.ipv4.tcp_max_syn_backlog = 65535 # SYN队列最大长度
net.ipv4.ip_local_port_range = 1024 65535 # 本地端口范围
net.ipv4.tcp_tw_reuse = 1 # 允许TIME-WAIT套接字重用
net.ipv4.tcp_fin_timeout = 30 # TIME-WAIT超时时间(秒)
运行sysctl -p使配置生效。net.ipv4.tcp_window_scaling=1开启窗口缩放)。go mod init <module-name>(如go mod init github.com/user/myapp),生成go.mod文件。go get下载依赖(自动添加到go.mod),go mod tidy清理未使用的依赖,确保依赖版本一致。~/.vim/syntax/go.vim),并在~/.vimrc中启用:syntax on
filetype plugin indent on
支持Go代码语法高亮,提升编码体验。