对象复用-基本使用

基本使用

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())
}

创建及销毁方法

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

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