Random Thoughts
Recent content on Random Thoughts
马上订阅 Random Thoughts RSS 更新: https://blog.joway.io/index.xml
Pond: Golang 通用对象池
2021年1月23日 08:00
为什么需要通用对象池
在实际生产环境中,我们经常会遇到需要多线程共享同一堆对象的场景,例如常见的RPC、数据库连接池,大内存对象池,以及线程池等。这些池化对象的需求其实有很多重叠的地方,主要分以下几个方面:
- 基础设置:
- 最大容量
- 创建/校验/删除对象的回调方法
- 申请对象时,已满时是否阻塞
- 多重驱逐策略:
- 驱逐闲置对象
- 驱逐无效对象
- 预创建对象
为避免重复编码,所以设计了 Pond 这样一个能够支撑多种使用场景的通用对象池。另外,在 Pond 的基础上,还实现了 Goroutine 池库: Hive。
使用方式
//example
type conn struct {
addr string
}
func main() {
ctx := context.Background()
cfg := pond.NewDefaultConfig()
cfg.MinIdle = 1
cfg.ObjectCreateFactory = func(ctx context.Context) (interface{}, error) {
return &conn{addr: "127.0.0.1"}, nil
}
cfg.ObjectValidateFactory = func(ctx context.Context, object interface{}) bool {
c := object.(...
剩余内容已隐藏
查看完整文章以阅读更多
Random Thoughts
Recent content on Random Thoughts
马上订阅 Random Thoughts RSS 更新: https://blog.joway.io/index.xml
Pond: Golang 通用对象池
2021年1月23日 08:00
为什么需要通用对象池
在实际生产环境中,我们经常会遇到需要多线程共享同一堆对象的场景,例如常见的RPC、数据库连接池,大内存对象池,以及线程池等。这些池化对象的需求其实有很多重叠的地方,主要分以下几个方面:
- 基础设置:
- 最大容量
- 创建/校验/删除对象的回调方法
- 申请对象时,已满时是否阻塞
- 多重驱逐策略:
- 驱逐闲置对象
- 驱逐无效对象
- 预创建对象
为避免重复编码,所以设计了 Pond 这样一个能够支撑多种使用场景的通用对象池。另外,在 Pond 的基础上,还实现了 Goroutine 池库: Hive。
使用方式
//example
type conn struct {
addr string
}
func main() {
ctx := context.Background()
cfg := pond.NewDefaultConfig()
cfg.MinIdle = 1
cfg.ObjectCreateFactory = func(ctx context.Context) (interface{}, error) {
return &conn{addr: "127.0.0.1"}, nil
}
cfg.ObjectValidateFactory = func(ctx context.Context, object interface{}) bool {
c := object.(...
剩余内容已隐藏
查看完整文章以阅读更多