Documentation
¶
Index ¶
- type Pool
- func (this *Pool) Capacity() int
- func (this *Pool) CheckExpire()
- func (this *Pool) Close()
- func (this *Pool) Get(wait time.Duration) interface{}
- func (this *Pool) Idle() int
- func (this *Pool) Put(x interface{})
- func (this *Pool) SetCapacity(capacity int) *Pool
- func (this *Pool) SetTTL(ttl time.Duration) *Pool
- func (this *Pool) Size() int
- func (this *Pool) TTL() time.Duration
- func (this *Pool) TryGet(wait time.Duration) (interface{}, bool)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
资源对象的缓存池
用于代替 sync.Pool 以便在复用的同时又能够及时释放资源。 网络连接池就是其中的一种典型场景: 为了在高并发情况下充分复用网络连接,调用方使用完毕后不会立即关闭网络连接,而是暂时放在资源池中,以便下次使 用时直接取出复用。 但如果业务在某个时刻对资源使用非常高、但在接下来的相当长时间内使用情况又非常低,这时候高峰期缓存的资源对象 就会在内存中迟迟得不到利用,此时反而降低了内存使用率。 Pool 通过定时器对 “放回到资源池中超过指定时间的对象” 进行释放,这样既能在高峰期及时复用、又能在低峰时及时释 放资源。
func New ¶
创建缓存池。
参数:
capacity: 最大创建的对象数。一旦超过该阈值,在 Get 时就会等待其他协程归还(Put)对象。 ttl: 对象在被放回 Pool 之后,过多久时间会被自动清除(从 Pool 中移除、并调用 del 方法释放对象)。 如果 TTL ≤ 0,则对象在调用 Pool.Put 方法时,会立即调用 del 方法进行释放、并且不会放回资源池,相当于 不使用缓存池。 new: 对象的创建方法。 del: 对象的释放方法。 如果 del 方法为 nil、且对象实现了 Close() 方法,则默认会使用 Close 方法释放;否则需在 del 内部自行 释放资源。
func (*Pool) CheckExpire ¶
func (this *Pool) CheckExpire()
func (*Pool) Get ¶
获取一个对象。
如果当前对象池中有空闲对象则直接返回,否则尝试构造新的对象。
参数:
wait: 等待时间。如果设置了 capacity、并且当前已经达到容量上限,则会等待其他协程归还(Put)对象。 wait = 0: 不等待,立即返回。 wait < 0: 一直等待,直到获得空闲对象。
func (*Pool) SetCapacity ¶
Click to show internal directories.
Click to hide internal directories.