pool

package
v0.0.0-...-8e1b2bd Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 7, 2024 License: BSD-3-Clause Imports: 4 Imported by: 0

Documentation

Index

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

func New(capacity int, ttl time.Duration, new func() interface{}, del func(x interface{})) *Pool

创建缓存池。

参数:

capacity:
   最大创建的对象数。一旦超过该阈值,在 Get 时就会等待其他协程归还(Put)对象。
ttl:
   对象在被放回 Pool 之后,过多久时间会被自动清除(从 Pool 中移除、并调用 del 方法释放对象)。
   如果 TTL ≤ 0,则对象在调用 Pool.Put 方法时,会立即调用 del 方法进行释放、并且不会放回资源池,相当于
   不使用缓存池。
new:
   对象的创建方法。
del:
   对象的释放方法。
   如果 del 方法为 nil、且对象实现了 Close() 方法,则默认会使用 Close 方法释放;否则需在 del 内部自行
   释放资源。

func (*Pool) Capacity

func (this *Pool) Capacity() int

func (*Pool) CheckExpire

func (this *Pool) CheckExpire()

func (*Pool) Close

func (this *Pool) Close()

关闭缓冲池

func (*Pool) Get

func (this *Pool) Get(wait time.Duration) interface{}

获取一个对象。

如果当前对象池中有空闲对象则直接返回,否则尝试构造新的对象。

参数:

wait: 等待时间。如果设置了 capacity、并且当前已经达到容量上限,则会等待其他协程归还(Put)对象。
   wait = 0: 不等待,立即返回。
   wait < 0: 一直等待,直到获得空闲对象。

func (*Pool) Idle

func (this *Pool) Idle() int

可复用的空闲对象个数

func (*Pool) Put

func (this *Pool) Put(x interface{})

归还对象

func (*Pool) SetCapacity

func (this *Pool) SetCapacity(capacity int) *Pool

func (*Pool) SetTTL

func (this *Pool) SetTTL(ttl time.Duration) *Pool

func (*Pool) Size

func (this *Pool) Size() int

已经从对缓存池中申请出去的对象个数

func (*Pool) TTL

func (this *Pool) TTL() time.Duration

func (*Pool) TryGet

func (this *Pool) TryGet(wait time.Duration) (interface{}, bool)

从缓冲池中获取一个对象。

如果当前对象池中有空闲对象则直接返回,否则尝试构造新的对象。

参数:

wait: 等待时间。如果设置了 capacity、并且当前已经达到容量上限,则会等待其他协程归还(Put)对象。
   wait = 0: 不等待,立即返回。
   wait < 0: 一直等待,直到获得空闲对象。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL