Documentation
¶
Overview ¶
Package pool manage reuseable resources like connections. Unlike other pool implementations, they fill the pool to full before reusing resources, this implementation only maintains possible minimal resources in the pool no matter how big the capacity is.
Example ¶
package main
import (
"fmt"
"time"
)
type SomeResource struct {
err error
}
func (r *SomeResource) Do() (res string, err error) {
// if err = doSth(); err != nil {
// r.err = err // NOTE: Must record the error if error is not nil.
// return
// }
res = "hello"
return
}
func (r *SomeResource) Err() error {
return r.err
}
func (r *SomeResource) Close() error {
return nil
}
func must(err error) {
if err != nil {
panic(err)
}
}
func main() {
pool, err := New(Options{
ResourceFactory: func() (Resource, error) {
return &SomeResource{}, nil
},
Capacity: 5,
IdleTimeout: 30 * time.Second,
})
must(err)
defer pool.Close()
r, err := pool.GetNoWait()
must(err)
defer pool.Put(r)
res, err := r.(*SomeResource).Do()
must(err)
fmt.Println(res)
}
Output: hello
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var ( // ErrPoolClosed indicates pool is closed. ErrPoolClosed = errors.New("pool closed") // ErrPoolIsBusy indicates no available resource in pool currently. ErrPoolIsBusy = errors.New("pool is busy") // ErrNoMatch indicates no Get/GetNoWait matched in previous call, // you will never see this error unless you do some thing wrong, // it will panic :-) ErrNoMatch = errors.New("no Get/GetNoWait matched") )
Functions ¶
This section is empty.
Types ¶
type Options ¶
type Options struct {
// ResourceFactory creates new resource.
ResourceFactory func() (Resource, error)
// Capacity sets the max pool size.
Capacity int
// IdleTimeout 0 indicate no idle timeout.
IdleTimeout time.Duration
// TestOnBorrow will test the resource before borrow and not idle for IdleTimeout,
// the resource must implement the TestableResource interface.
TestOnBorrow bool
// TestWhileIdle will test the resource if resource idle for IdleTimeout before borrow,
// if IdleTimeout less and equal than 0, this option is ignored.
// the resource must implement the TestableResource interface.
TestWhileIdle bool
}
Options is used to configurate the Pool. Set TestOnBorrow(true), TestWhileIdle(true) and IdleTimeout(>0) together will always test the resource if resource is testable.
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool is the container for resources.
type TestableResource ¶
TestableResource indicates the resource is testable, Test() will be called before every old resource return if TestOnBorrow/TestWhileIdle is set.
Click to show internal directories.
Click to hide internal directories.