---
title: "对象复用-基本使用"
url: "https://goframe.org/docs/components/container-gpool-example"
markdown_url: "https://goframe.org/docs/components/container-gpool-example.md"
locale: "zh-Hans"
version: "2.10.x(Latest)"
section: "组件列表"
category: "组件列表 / 数据结构 / 对象复用-gpool"
published: "2024-10-21"
updated: "2026-01-27"
description: "在GoFrame框架中使用gpool进行对象复用。在示例中，我们创建和操作了一个对象池，展示了对象的获取、返回及过期处理方法。此方法对于管理短生命周期的资源非常有效，可以显著提高程序性能和资源利用率。"
keywords: ["对象复用", "GoFrame", "GoFrame框架", "gpool", "对象池", "Go语言", "golang", "网络连接", "资源管理", "编程教程"]
---

# 对象复用-基本使用

## 基本使用

```go
package main

import (
    "github.com/gogf/gf/v2/container/gpool"
    "fmt"
    "time"
)

func main () {
    // 创建一个对象池，过期时间为1秒
    p := gpool.New(time.Second, nil)

    // 从池中取一个对象，返回nil及错误信息
    fmt.Println(p.Get())

    // 丢一个对象到池中
    p.Put(1)

    // 重新从池中取一个对象，返回1
    fmt.Println(p.Get())

    // 等待2秒后重试，发现对象已过期，返回nil及错误信息
    time.Sleep(2*time.Second)
    fmt.Println(p.Get())
}
```

## 创建及销毁方法

我们可以给定动态创建及销毁方法。

```go
package main

import (
    "fmt"
    "github.com/gogf/gf/v2/container/gpool"
    "github.com/gogf/gf/v2/net/gtcp"
    "github.com/gogf/gf/v2/os/glog"
    "time"
)

func main() {
    // 创建对象复用池，对象过期时间为3秒，并给定创建及销毁方法
    p := gpool.New(3*time.Second, func() (interface{}, error) {
        return gtcp.NewConn("www.baidu.com:80")
    }, func(i interface{}) {
        glog.Println("expired")
        i.(*gtcp.Conn).Close()
    })
    conn, err := p.Get()
    if err != nil {
        panic(err)
    }
    result, err := conn.(*gtcp.Conn).SendRecv([]byte("HEAD / HTTP/1.1\n\n"), -1)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(result))
    // 丢回池中以便重复使用
    p.Put(conn)
    // 等待一定时间观察过期方法调用
    time.Sleep(4*time.Second)
}
```

执行后，终端输出结果：

```
HTTP/1.1 302 Found
Connection: Keep-Alive
Content-Length: 17931
Content-Type: text/html
Date: Wed, 29 May 2019 11:23:20 GMT
Etag: "54d9749e-460b"
Server: bfe/1.0.8.18

2019-05-29 19:23:24.732 expired
```

## 泛型使用示例

:::tip
版本要求：`v2.10.0`
:::

从 `v2.10.0` 版本开始，`gpool` 提供了泛型类型 `TPool[T]`，无需类型断言，更加类型安全。

### 基本泛型使用

```go
package main

import (
    "fmt"
    "time"
    
    "github.com/gogf/gf/v2/container/gpool"
)

func main() {
    // 创建一个泛型对象池，过期时间为1秒
    p := gpool.NewTPool[int](
        time.Second,
        nil, // 不指定创建方法
    )

    // 从池中取一个对象，返回零值及错误信息
    fmt.Println(p.Get())

    // 丢一个对象到池中
    p.Put(1)

    // 重新从池中取一个对象，返回 1
    fmt.Println(p.Get())

    // 等待2秒后重试，发现对象已过期，返回零值及错误信息
    time.Sleep(2 * time.Second)
    fmt.Println(p.Get())
}
```

### 泛型对象池示例

```go
package main

import (
    "fmt"
    "time"
    
    "github.com/gogf/gf/v2/container/gpool"
    "github.com/gogf/gf/v2/net/gtcp"
    "github.com/gogf/gf/v2/os/glog"
)

func main() {
    // 创建对象复用池，对象过期时间为3秒，并给定创建及销毁方法
    p := gpool.NewTPool[*gtcp.Conn](
        3*time.Second,
        func() (*gtcp.Conn, error) {
            return gtcp.NewConn("www.baidu.com:80")
        },
        func(conn *gtcp.Conn) {
            glog.Println("expired")
            conn.Close()
        },
    )
    
    conn, err := p.Get()
    if err != nil {
        panic(err)
    }
    
    // 无需类型断言，conn 已经是 *gtcp.Conn 类型
    result, err := conn.SendRecv([]byte("HEAD / HTTP/1.1\n\n"), -1)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(result))
    
    // 丢回池中以便重复使用
    p.Put(conn)
    
    // 等待一定时间观察过期方法调用
    time.Sleep(4 * time.Second)
}
```

### 自定义结构体示例

```go
package main

import (
    "fmt"
    "time"
    
    "github.com/gogf/gf/v2/container/gpool"
)

type User struct {
    ID   int
    Name string
}

func main() {
    // 创建 User 对象池
    pool := gpool.NewTPool[*User](
        5*time.Second,
        func() (*User, error) {
            return &User{
                ID:   1,
                Name: "default",
            }, nil
        },
        func(user *User) {
            fmt.Printf("清理用户对象: %+v\n", user)
        },
    )
    defer pool.Close()

    // 获取对象
    user, err := pool.Get()
    if err != nil {
        panic(err)
    }
    
    // 直接使用，无需类型断言
    fmt.Printf("用户ID: %d, 名称: %s\n", user.ID, user.Name)
    
    // 修改对象
    user.ID = 100
    user.Name = "张三"
    
    // 放回池中复用
    pool.MustPut(user)
    
    // 再次获取，得到刚才修改的对象
    user2, _ := pool.Get()
    fmt.Printf("复用对象 - ID: %d, 名称: %s\n", user2.ID, user2.Name)
}
```
