-
Notifications
You must be signed in to change notification settings - Fork 6
/
postgres.go
91 lines (78 loc) · 1.66 KB
/
postgres.go
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package holo
import (
"database/sql"
"database/sql/driver"
"encoding/json"
"fmt"
"time"
"github.com/lib/pq"
_ "github.com/lib/pq"
"github.com/alibaba/pairec/v2/log"
"github.com/alibaba/pairec/v2/recconf"
)
func init() {
//sql.Register("hologres", &HologresDriver{})
}
type HologresDriver struct {
driver pq.Driver
}
func (d HologresDriver) Open(name string) (driver.Conn, error) {
conn, err := d.driver.Open(name)
if err != nil {
return nil, err
}
if stmt, err := conn.Prepare("set statement_timeout = 500"); err == nil {
stmt.Exec(nil)
stmt.Close()
}
return conn, err
}
type Postgres struct {
DSN string
DB *sql.DB
Name string
}
var postgresqlInstances = make(map[string]*Postgres)
func GetPostgres(name string) (*Postgres, error) {
if _, ok := postgresqlInstances[name]; !ok {
return nil, fmt.Errorf("Postgres not found, name:%s", name)
}
return postgresqlInstances[name], nil
}
func (m *Postgres) Init() error {
db, err := sql.Open("hologres", m.DSN)
if err != nil {
return err
}
db.SetConnMaxLifetime(60 * time.Minute)
db.SetMaxIdleConns(50)
db.SetMaxOpenConns(100)
m.DB = db
err = m.DB.Ping()
go m.loopDBStats()
return err
}
func (m *Postgres) loopDBStats() {
for {
stat := m.DB.Stats()
j, _ := json.Marshal(stat)
log.Info(fmt.Sprintf("event=dbstat\tname=%s\tmsg=%s", m.Name, string(j)))
time.Sleep(10 * time.Second)
}
}
func Load(config *recconf.RecommendConfig) {
for name, conf := range config.HologresConfs {
if _, ok := postgresqlInstances[name]; ok {
continue
}
m := &Postgres{
DSN: conf.DSN,
Name: name,
}
err := m.Init()
if err != nil {
panic(err)
}
postgresqlInstances[name] = m
}
}