-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.go
More file actions
39 lines (33 loc) · 765 Bytes
/
node.go
File metadata and controls
39 lines (33 loc) · 765 Bytes
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
package pgbalancer
import (
"database/sql"
"fmt"
"sync"
_ "github.com/lib/pq"
"golang.org/x/time/rate"
)
type Node struct {
name string
db *sql.DB
mu sync.RWMutex
limiter *rate.Limiter
}
func newNode(name string, dsn string, limitRPS int, maxIdleConn int, maxOpenConn int) (*Node, error) {
db, err := sql.Open("postgres", dsn)
if err != nil {
return nil, fmt.Errorf("open db: %w", err)
}
if err := db.Ping(); err != nil {
return nil, fmt.Errorf("ping db: %w", err)
}
db.SetMaxIdleConns(maxIdleConn)
db.SetMaxOpenConns(maxOpenConn)
n := &Node{db: db, name: name}
n.setLimit(limitRPS)
return n, nil
}
func (n *Node) setLimit(limitRPS int) {
l := rate.Limit(limitRPS)
limiter := rate.NewLimiter(l, 1)
n.limiter = limiter
}