Created
March 2, 2019 00:50
-
-
Save posilva/b26fe5ae731b7a7126566a6180188ee6 to your computer and use it in GitHub Desktop.
Example of the usage of go-poolboy to wrap connections to a database and have a dedicated pool of workers to connect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"fmt" | |
_ "github.com/go-sql-driver/mysql" | |
poolboy "github.com/posilva/go-poolboy" | |
"strconv" | |
) | |
type DBConfig struct { | |
host string | |
usr string | |
pwd string | |
port int | |
db string | |
} | |
type DBPool struct { | |
pool *poolboy.Pool | |
} | |
func newDBPool() *DBPool { | |
return &DBPool{ | |
pool: poolboy.NewPool(10), | |
} | |
} | |
func (p *DBPool) Query(sqlStmt string) (*sql.Rows, error) { | |
r, err := p.pool.Execute(func(s interface{}) (interface{}, error) { | |
db := s.(*sql.DB) | |
return db.Query(sqlStmt) | |
}, 1000) | |
if err != nil { | |
return nil, err | |
} | |
return r.(*sql.Rows), err | |
} | |
func (p *DBPool) Dispose() { | |
p.pool.Cancel() | |
} | |
func (p *DBPool) Setup(c DBConfig) error { | |
//"root:password1@tcp(127.0.0.1:3306)/test" | |
connStr := c.usr + ":" + c.pwd + "@tcp(" + c.host + ":" + strconv.Itoa(c.port) + ")/" + c.db | |
fmt.Print(connStr) | |
return p.pool.Init(func() (interface{}, error) { | |
db, err := sql.Open("mysql", connStr) | |
if err != nil { | |
fmt.Printf("error: %v", err) | |
return nil, fmt.Errorf("failed to open database: %v", err) | |
} | |
db.Ping() | |
return db, nil | |
}) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
_ "github.com/go-sql-driver/mysql" | |
) | |
func main() { | |
p := newDBPool() | |
c := DBConfig{ | |
db: "mydb", | |
host: "127.0.0.1", | |
port: 3306, | |
usr: "root", | |
pwd: "passw", | |
} | |
err := p.Setup(c) | |
if err != nil { | |
panic(err) | |
} | |
defer p.Dispose() | |
r, e := p.Query("SELECT 1 FROM DUAL") | |
if e != nil { | |
panic(e.Error()) | |
} | |
defer r.Close() | |
fmt.Println(r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment