直接起goroutine处理请求会导致内存暴涨、调度过载甚至OOM,因Go不限流且goroutine有栈开销;应使用带缓冲channel+固定worker池限流,并结合context与errgroup实现超时控制和优雅退出。
大量并发请求下,go handleRequest(req) 会无节制创建 goroutine,内存暴涨、调度器过载、甚至 OOM。Go runtime 不会自动限流,runtime.GOMAXPROCS 控制的是 OS 线程数,不是 goroutine 并发上限。
fatal error: runtime: out of memory 或 schedule: holding locks 日志核心是把请求封装为任务,投递到带缓冲的 chan *http.Request(或自定义任务结构),由固定数量的 worker 从 channel 中取任务执行。
type WorkerPool struct {
tasks chan *http.Request
workers int
}
func NewWorkerPool(size int) WorkerPool {
return &WorkerPool{
tasks: make(chan http.Request, 1000), // 缓冲区防阻塞生产者
workers: size,
}
}
func (wp *WorkerPool) Start() {
for i := 0; i < wp.workers; i++ {
go func() {
for req := range wp.tasks {
// 实际处理逻辑,如解析、DB 查询、响应写入
http.Error(req.Response, "OK", http.StatusOK)
}
}()
}
}
func (wp WorkerPool) Submit(req http.Request) {
select {
case wp.tasks <- req:
// 成功入队
default:
// 队列满,拒绝或降级(如返回 503)
http.Error(req.Response, "Service Unavailable", http.StatusServiceUnavailable)
}
}
make(chan *http.Request, 1000) 的缓冲大小需根据平均处理时长和 QPS 估算,太小易丢任务,太大吃内存select {... default: ...} 是非阻塞提交的关键,避免 handler 卡死runtime.NumCPU() * 2 左右,过高反而因上下文切换降低吞吐单纯 channel 池无法优雅中断正在运行的任务。需结合 context.Context 和 errgroup.Group 实现整体超时与传播取消信号。
func (wp *WorkerPool) SubmitWithContext(ctx context.Context, req *http.Request) error {
// 包装请求上下文,携带超时与取消
req = req.WithContext(ctx)
select {
case wp.tasks <- req:
return nil
default:
return errors.New("task queue full")
}}
// 启动时改用 errgroup
func (wp WorkerPool) StartWithGroup(g errgroup.Group) {
for i := 0; i
req.WithContext(ctx) 确保下游 DB、HTTP 客户端等能感知超时
errgroup 可统一等待所有 worker 退出,并捕获任意 worker panic 或 errorreq, ok := 中 ok 为 false,应退出 goroutine
goroutine 池只是应用层限流,若底层 TCP 连接不控,仍可能被慢连接打垮。必须配置 http.Server 的各项超时与限制。
server := &http.Server{
Addr: ":8080",
Handler: myHandler,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 30 * time.Second,
MaxHeaderBytes: 1 << 20, // 1MB
ConnState: func(conn net.Conn, state http.ConnState) {
if state == http.StateNew {
// 可在此做连接数硬限(如 atomic.AddInt64(&connCount, 1) > 10000 → close)
}
},
}ReadTimeout 防慢请求头/体,WriteTimeout 防慢响应,IdleTimeout 防长连接耗尽 fdMaxHeaderBytes 必须设,否则恶意大 header 可轻易触发 OOMgoroutine 池的边界很清晰:它只管“我有多少个工人能同时干活”,不管“谁来敲门”“门开了多久”“进门后赖着不走”。漏掉任一层,都可能让精心设计的池子毫无意义。