性能分析
import _ "net/http/pprof"
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
// 访问 http://localhost:6060/debug/pprof/
内存优化
// 使用 sync.Pool 复用对象
var bufferPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
buf := bufferPool.Get().(*bytes.Buffer)
defer bufferPool.Put(buf)
buf.Reset()
并发控制
// 限制并发数
semaphore := make(chan struct{}, 10)
for _, task := range tasks {
semaphore <- struct{}{}
go func(t Task) {
defer func() { <-semaphore }()
process(t)
}(task)
}
优雅关闭
srv := &http.Server{Addr: ":8080"}
go func() {
if err := srv.ListenAndServe(); err != nil {
log.Printf("服务器错误: %v", err)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
srv.Shutdown(ctx)
最佳实践
- 使用 context 管理超时和取消
- 避免 goroutine 泄漏
- 合理使用缓冲通道
- 注意并发安全
- 使用 defer 确保资源释放