-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
64 lines (52 loc) · 1.37 KB
/
client.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
package goo_clickhouse
import (
"database/sql"
"fmt"
"github.com/ClickHouse/clickhouse-go"
goo_cron "github.com/liqiongtao/googo.io/goo-cron"
goo_log "github.com/liqiongtao/googo.io/goo-log"
)
type client struct {
conf Config
db *sql.DB
}
func New(conf Config) (cli *client, err error) {
if conf.ReadTimeout == 0 {
conf.ReadTimeout = 10
}
if conf.WriteTimeout == 0 {
conf.WriteTimeout = 20
}
cli = &client{conf: conf}
if err = cli.connect(); err != nil {
return
}
if conf.AutoPing {
goo_cron.Default().SecondX(5, __client.ping).Start()
}
return
}
func (cli *client) connect() (err error) {
dns := fmt.Sprintf("tcp://%s?username=%s&password=%s&database=%s&read_timeout=%d&write_timeout=%d&alt_hosts=%s&debug=%v",
cli.conf.Addr, cli.conf.User, cli.conf.Password, cli.conf.Database,
cli.conf.ReadTimeout, cli.conf.WriteTimeout, cli.conf.AltHosts, cli.conf.Debug)
cli.db, err = sql.Open(cli.conf.Driver, dns)
if err != nil {
goo_log.WithTag("goo-clickhouse").Error(err)
}
return
}
func (cli *client) ping() {
if cli.db == nil {
return
}
err := cli.db.Ping()
if err == nil {
return
}
if exception, ok := err.(*clickhouse.Exception); ok {
goo_log.WithTag("goo-clickhouse").WithField("err_code", exception.Code).WithField("stack_trace", exception.StackTrace).Error(exception.Message)
return
}
goo_log.WithTag("goo-clickhouse").Error(err)
}