Pool
Pool is a simple and generic connection pool written in Golang. It can be used to manage and reuse resources that are expensive to create or destroy, such as network connections or database connections.
⚠️ This README file was generated by ChatGPT. I cannot guarantee that everything is correct. Use this library at your own risk, and please report any issues or inaccuracies you may find.
Installation
To install the package, run the following command:
go get github.com/cdfmlr/pool
Usage
To use the pool, create a new pool instance using the NewPool function and provide two arguments: the maximum number of resources that can be created and a function that creates new resources.
maxLen := 10
createFunc := func() (Poolable, error) {
// create new resource
}
p := NewPool(maxLen, createFunc)
Once you've created the pool, you can use the following methods to interact with it:
Get() (T, error) - Get a resource from the pool. If the pool is empty, a new resource will be created if the maximum pool size has not been reached.
Put(T) error - Put a resource back into the pool. If the pool is full, the resource will be closed and discarded.
Release(T) error - Release an unused resource from the pool and close it. Releasing a resource that was not obtained from the pool will break the consistency of the pool.
Len() int - Get the current size of the pool.
Idle() int- Get the current number of idle resources in the pool.
Close() error - Close the pool and release all resources.
Example
package main
import (
"fmt"
"github.com/cdfmlr/pool"
)
type MyResource struct {
id int
}
func (r *MyResource) Close() error {
fmt.Printf("Closing resource %d\n", r.id)
return nil
}
func main() {
maxLen := 2
createFunc := func() (pool.Poolable, error) {
return &MyResource{id: 0}, nil
}
p := pool.NewPool(maxLen, createFunc)
// Get a resource from the pool
r1, err := p.Get()
if err != nil {
panic(err)
}
fmt.Printf("Got resource %d\n", r1.(*MyResource).id)
// Put the resource back into the pool
if err := p.Put(r1); err != nil {
panic(err)
}
fmt.Printf("Put resource %d back into the pool\n", r1.(*MyResource).id)
// Get another resource from the pool
r2, err := p.Get()
if err != nil {
panic(err)
}
fmt.Printf("Got resource %d\n", r2.(*MyResource).id)
// Release the resource back intothe pool and close it
if err := p.Release(r2); err != nil {
panic(err)
}
fmt.Printf("Released and closed resource %d\n", r2.(*MyResource).id)
// Close the pool and release all resources
if err := p.Close(); err != nil {
panic(err)
}
}
Error Handling
The following errors may be returned by methods in the Pool interface:
ErrPoolClosed - The pool has been closed and no new resources can be obtained.
ErrPoolExhausted - The pool has reached its maximum capacity and no new resources can be created.