/
etcd.go
53 lines (46 loc) · 1 KB
/
etcd.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
package etcd
import (
"context"
"time"
"github.com/spf13/viper"
clientv3 "go.etcd.io/etcd/client/v3"
)
type Option struct {
EndPoints []string
Username string
Password string
DialTimeout time.Duration
}
func NewOption(v *viper.Viper) (*Option, error) {
var (
err error
o = new(Option)
)
if err = v.UnmarshalKey("etcd", o); err != nil {
return nil, err
}
o.DialTimeout *= time.Second
return o, nil
}
func New(o *Option) (*clientv3.Client, error) {
var (
err error
client *clientv3.Client
)
if client, err = clientv3.New(clientv3.Config{
Endpoints: o.EndPoints,
DialTimeout: o.DialTimeout,
Username: o.Username,
Password: o.Password,
}); err != nil {
return nil, err
}
// 启动的时候,去连接一下etcd,否则之后,etcd连接不上会导致程序阻塞
ctx, cancel := context.WithTimeout(context.Background(), o.DialTimeout)
defer cancel()
_, err = client.Status(ctx, o.EndPoints[0])
if err != nil {
return nil, err
}
return client, nil
}