sync包的Pool
# sync.Pool
# 基本用法
# 概念
协程安全、可伸缩的,用于存放可重用对象的容器。
原始目的
存放已分配但是暂时不用的对象,需要时直接从
pool
里取,然后放回,以减小 GC 回收的压力。
GC 压力是啥
很简单,对象多了,GC 回收自然压力就大
提示
可以去了解一下内存标记
var p *sync.Pool
type User struct {
Name string
}
func main() {
p = &sync.Pool{
New: func() interface{} {
log.Println("create user")
return &User{Name: "张三"}
},
}
u1 := p.Get().(*User)
fmt.Println(u1)
u1.Name = "李四"
p.Put(u1)
u2 := p.Get()
fmt.Println(u2)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 简单实用场景
常用的gin
框架里的r := gin.New()
方法里就使用了
func New() *Engine {
debugPrintWARNINGNew()
engine := &Engine{
RouterGroup: RouterGroup{
Handlers: nil,
basePath: "/",
root: true,
},
FuncMap: template.FuncMap{},
RedirectTrailingSlash: true,
RedirectFixedPath: false,
HandleMethodNotAllowed: false,
ForwardedByClientIP: true,
RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"},
TrustedPlatform: defaultPlatform,
UseRawPath: false,
RemoveExtraSlash: false,
UnescapePathValues: true,
MaxMultipartMemory: defaultMultipartMemory,
trees: make(methodTrees, 0, 9),
delims: render.Delims{Left: "{{", Right: "}}"},
secureJSONPrefix: "while(1);",
trustedProxies: []string{"0.0.0.0/0", "::/0"},
trustedCIDRs: defaultTrustedCIDRs,
}
engine.RouterGroup.engine = engine
engine.pool.New = func() any {
return engine.allocateContext()
}
return engine
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// ServeHTTP conforms to the http.Handler interface.
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
c := engine.pool.Get().(*Context)
c.writermem.reset(w)
c.Request = req
c.reset()
engine.handleHTTPRequest(c)
engine.pool.Put(c)
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
所以它每次有连接进来都不是每次都创建一个
context
编辑 (opens new window)
上次更新: 2022/09/04, 12:06:50