新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)GoFrame教程:GoFramegpool-基本使用
基本使用
package main
import (
"github.com/GOgf/gf/v2/container/gpool"
"fmt"
"time"
)
func main () {
// 創(chuàng)建一個對象池,過期時間為1秒
p := gpool.New(time.Second, nil)
// 從池中取一個對象,返回nil及錯誤信息
fmt.Println(p.Get())
// 丟一個對象到池中
p.Put(1)
// 重新從池中取一個對象,返回1
fmt.Println(p.Get())
// 等待2秒后重試,發(fā)現(xiàn)對象已過期,返回nil及錯誤信息
time.Sleep(2*time.Second)
fmt.Println(p.Get())
}
創(chuàng)建及銷毀方法
我們可以給定動態(tài)創(chuàng)建及銷毀方法。

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() {
// 創(chuàng)建對象復用池,對象過期時間為3秒,并給定創(chuàng)建及銷毀方法
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)
}執(zhí)行后,終端輸出結果:
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 當前名稱:創(chuàng)新互聯(lián)GoFrame教程:GoFramegpool-基本使用
本文鏈接:http://m.fisionsoft.com.cn/article/cdjesjj.html


咨詢
建站咨詢
