xfy 4a93cf2b5c refactor(variable): 简化变量池函数
- PoolGet() 改为调用 NewContext()
- PoolPut() 改为调用 ReleaseContext()
- 添加 Deprecated 文档注释

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-10 11:20:50 +08:00

80 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Package variable 提供 sync.Pool 用于复用 Context减少 GC 压力。
//
// 包含池统计信息、Get/Put 包装方法和统计重置功能。
//
// 作者xfy
package variable
import (
"sync"
"github.com/valyala/fasthttp"
)
// PoolStats 池统计信息
type PoolStats struct {
Gets int64 // Get 次数
Puts int64 // Put 次数
NewCount int64 // New 创建次数
Active int64 // 当前活跃数量 (Gets - Puts)
}
var (
// stats 池统计
stats PoolStats
// statsMu 保护统计信息
statsMu sync.RWMutex
)
// GetStats 获取池统计信息
func GetStats() PoolStats {
statsMu.RLock()
s := stats
statsMu.RUnlock()
return s
}
// GetPool 获取底层的 sync.Pool用于测试和调试
func GetPool() *sync.Pool {
return &pool
}
// PoolGet 从池中获取 Context包装方法用于统计
//
// Deprecated: 使用 NewContext 代替,该函数保持向后兼容。
func PoolGet(ctx *fasthttp.RequestCtx) *Context {
vc := NewContext(ctx)
// 更新统计
statsMu.Lock()
stats.Gets++
stats.Active = stats.Gets - stats.Puts
statsMu.Unlock()
return vc
}
// PoolPut 将 Context 放回池中(包装方法,用于统计)
//
// Deprecated: 使用 ReleaseContext 代替,该函数保持向后兼容。
func PoolPut(vc *Context) {
if vc == nil {
return
}
ReleaseContext(vc)
// 更新统计
statsMu.Lock()
stats.Puts++
stats.Active = stats.Gets - stats.Puts
statsMu.Unlock()
}
// ResetStats 重置统计信息
func ResetStats() {
statsMu.Lock()
stats = PoolStats{}
statsMu.Unlock()
}