Documentation ¶
Overview ¶
This is a simple implementation of connection pool.
First, the user needs to implement the ConnManager interface so that the pool can know how to create a connection and how to initialize a connection.
After that, simply use “Get()“ function to get an initialized connection. The connection will be initiallized by the “InitConn()“ method provided by the “ConnManager“.
For each connection allocated from the pool, the user *must* call “Close()“ in the end, otherwise the connection will not be returned back to the pool.
Example:
type ServerConnManager struct { addr string } func (self *ServerConnManager) NewConn() (conn net.Conn, err error) { return net.Dial("tcp", self.addr) } func (self *ServerConnManager) InitConn(conn net.Conn, n int) error { _, err := conn.Write([]byte("IDLE")) return err }
To use the pool:
manager := &ServerConnManager{"example.com:80"} pool := NewPool(0, 1024, manager) conn, err := pool.Get() defer conn.Close() if err != nil { // Do something }
Index ¶
Constants ¶
This section is empty.
Variables ¶
Functions ¶
This section is empty.
Types ¶
type ConnManager ¶
type ConnManager interface { // Used to create a new connection. // It will be called if there is no enough connection // ans there is still space to allocate new connections. NewConn() (net.Conn, error) // This method will be called when the user // use Pool.Get() to get a connection. // Every connection returned from Get() will // be initialized with this method. // // conn is the connection, which will be returned. // // n is the number of times this connection has been used. // n = 0 means the connection is newly created. InitConn(conn net.Conn, n int) error }
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
func NewPool ¶
func NewPool(maxNrConn, maxNrIdle int, mngr ConnManager) *Pool
Create a new connection pool, which will never create more than maxNrConn connections and will always maintain less than maxNrIdle idle connections.
maxNrIdle <= 0 means there is no limit on max number of idle connections.
maxNrConn <= means there is no limit on max number of connections.
func (*Pool) Get ¶
Get a connection. The function will block the goroutine until there is a connection available or an error occured. Calling Get() on a closed pool will lead to panic.
func (*Pool) ShouldAcceptTempError ¶
If this is set to true, then a connection will be reused if it has a temporary error. Otherwise, the connection will be dropped on a temporary error.