gf/.example/container/gpool/gpool_expirefunc.go

34 lines
744 B
Go
Raw Normal View History

2019-05-31 22:54:57 +08:00
package main
import (
"fmt"
"time"
2019-07-29 21:01:19 +08:00
"github.com/gogf/gf/container/gpool"
"github.com/gogf/gf/net/gtcp"
"github.com/gogf/gf/os/glog"
2019-05-31 22:54:57 +08:00
)
func main() {
// 创建对象复用池对象过期时间为3000毫秒并给定创建及销毁方法
p := gpool.New(3000, 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)
// 等待一定时间观察过期方法调用
2019-06-12 21:06:57 +08:00
time.Sleep(4 * time.Second)
2019-05-31 22:54:57 +08:00
}