-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpool_example.go
More file actions
54 lines (50 loc) · 1.34 KB
/
pool_example.go
File metadata and controls
54 lines (50 loc) · 1.34 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main
import (
"fmt"
"log"
"sync"
"github.com/jbarham/pgsql.go"
)
func main() {
// Create a connection pool with up to 3 connections, automatically closing
// idle connections after the default timeout period (5 minutes).
pool, err := pgsql.NewPool("dbname=testdb", 3, pgsql.DEFAULT_IDLE_TIMEOUT)
if err != nil {
log.Fatalf("Error opening connection pool: %s\n", err)
}
// Create 10 worker goroutines each of which acquires and uses a
// connection from the pool.
var wg sync.WaitGroup
nthreads := 10
wg.Add(nthreads)
for i := 0; i < nthreads; i++ {
go worker(i+1, pool, &wg)
}
wg.Wait() // Wait for all the workers to finish.
pool.Close() // Close all pool connections.
}
func worker(id int, pool *pgsql.Pool, wg *sync.WaitGroup) {
conn, err := pool.Acquire()
if err != nil {
log.Printf("Error acquiring connection: %s\n", err)
} else {
res, err := conn.Query("SELECT now()")
if err != nil {
log.Printf("Error executing query: %s\n", err)
} else {
if !res.Next() {
log.Println("Couldn't advance result cursor")
} else {
var now string
if err := res.Scan(&now); err != nil {
log.Printf("Error scanning result: %s\n", err)
} else {
fmt.Printf("Timestamp returned for worker %d: %s\n", id, now)
}
}
}
}
// Return the connection back to the pool.
pool.Release(conn)
wg.Done()
}