github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/pool/bufferpool/bufferpool.go (about) 1 package bufferpool 2 3 /* 缓存池,避免重复申请内存,减轻gc压力 4 * 一个sync.Pool对象就是一组临时对象的集合。Pool是协程安全的 5 * 注意事项:获取资源Get后,必须执行Put放回操作 6 */ 7 import ( 8 "bytes" 9 "sync" 10 ) 11 12 type BufferPool struct { 13 sync.Pool 14 } 15 16 //声明一块bufferpool大小 17 func NewBufferPool(bufferSize int) (bufferpool *BufferPool) { 18 return &BufferPool{ 19 sync.Pool{ 20 New: func() interface{} { 21 return bytes.NewBuffer(make([]byte, 0, bufferSize)) 22 }, 23 }, 24 } 25 } 26 27 //获取一块buffer写入 28 func (bufferpool *BufferPool) Get() *bytes.Buffer { 29 return bufferpool.Pool.Get().(*bytes.Buffer) 30 } 31 32 //放回buffer重用 33 func (bufferpool *BufferPool) Put(b *bytes.Buffer) { 34 b.Reset() 35 bufferpool.Pool.Put(b) 36 }