public
Last active

Abstract wrapper to allow connection pools

  • Download Gist
gistfile1.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
type InitFunction func() (interface{}, error)
 
type ConnectionPoolWrapper struct {
size int
conn 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.conn = 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.conn <- conn
}
p.size = size
return nil
}
 
func (p *ConnectionPoolWrapper) GetConnection() interface{} {
return <-p.conn
}
 
func (p *ConnectionPoolWrapper) ReleaseConnection(conn interface{}) {
p.conn <- conn
}
 
var dbPool = &ConnectionPoolWrapper{}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.