Skip to content

Instantly share code, notes, and snippets.

@shaunlee
Forked from rday/gist:3504674
Last active September 10, 2017 21:35
Show Gist options
  • Save shaunlee/6260565 to your computer and use it in GitHub Desktop.
Save shaunlee/6260565 to your computer and use it in GitHub Desktop.
Connection Pool
type InitFunction func() (interface{}, error)
type ConnectionPoolWrapper struct {
size int
pool chan interface{}
}
/**
Call the init function size times. If the init function fails during any call, then
the creation of the pool is considered a failure.
We call the same function size times to make sure each connection shares the same
state.
*/
func (p *ConnectionPoolWrapper) InitPool(size int, initfn InitFunction) error {
// Create a buffered channel allowing size senders
p.pool = make(chan interface{}, size)
for x := 0; x < size; x++ {
conn, err := initfn()
if err != nil {
return err
}
// If the init function succeeded, add the connection to the channel
p.pool <- conn
}
p.size = size
return nil
}
func (p *ConnectionPoolWrapper) GetConnection() interface{} {
return <-p.pool
}
func (p *ConnectionPoolWrapper) ReleaseConnection(conn interface{}) {
p.pool <- conn
}
var dbPool = &ConnectionPoolWrapper{}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment