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

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)建對(duì)象復(fù)用池,對(duì)象過(guò)期時(shí)間為3秒,并給定創(chuàng)建及銷(xiāo)毀方法
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))
// 丟回池中以便重復(fù)使用
p.Put(conn)
// 等待一定時(shí)間觀察過(guò)期方法調(diào)用
time.Sleep(4*time.Second)
}執(zhí)行后,終端輸出結(jié)果:
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 當(dāng)前文章:創(chuàng)新互聯(lián)GoFrame教程:GoFramegpool-基本使用
轉(zhuǎn)載來(lái)源:http://www.5511xx.com/article/cdjesjj.html


咨詢
建站咨詢
