Basic Usage

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/container/gpool"
  4. "fmt"
  5. "time"
  6. )
  7. func main () {
  8. // Create an object pool with an expiration time of 1 second
  9. p := gpool.New(time.Second, nil)
  10. // Get an object from the pool, return nil and error information
  11. fmt.Println(p.Get())
  12. // Put an object into the pool
  13. p.Put(1)
  14. // Get an object from the pool again, return 1
  15. fmt.Println(p.Get())
  16. // After waiting for 2 seconds, try again and find the object has expired, return nil and error information
  17. time.Sleep(2*time.Second)
  18. fmt.Println(p.Get())
  19. }

Create and Destroy Methods

We can specify dynamic create and destroy methods.

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/container/gpool"
  5. "github.com/gogf/gf/v2/net/gtcp"
  6. "github.com/gogf/gf/v2/os/glog"
  7. "time"
  8. )
  9. func main() {
  10. // Create an object reuse pool with an object expiration time of 3 seconds, and specify create and destroy methods
  11. p := gpool.New(3*time.Second, func() (interface{}, error) {
  12. return gtcp.NewConn("www.baidu.com:80")
  13. }, func(i interface{}) {
  14. glog.Println("expired")
  15. i.(*gtcp.Conn).Close()
  16. })
  17. conn, err := p.Get()
  18. if err != nil {
  19. panic(err)
  20. }
  21. result, err := conn.(*gtcp.Conn).SendRecv([]byte("HEAD / HTTP/1.1\n\n"), -1)
  22. if err != nil {
  23. panic(err)
  24. }
  25. fmt.Println(string(result))
  26. // Put back into the pool for reuse
  27. p.Put(conn)
  28. // Wait for a while to observe the expiration method call
  29. time.Sleep(4*time.Second)
  30. }

After execution, the terminal outputs:

  1. HTTP/1.1 302 Found
  2. Connection: Keep-Alive
  3. Content-Length: 17931
  4. Content-Type: text/html
  5. Date: Wed, 29 May 2019 11:23:20 GMT
  6. Etag: "54d9749e-460b"
  7. Server: bfe/1.0.8.18
  8. 2019-05-29 19:23:24.732 expired