/
root.go
81 lines (73 loc) · 1.59 KB
/
root.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
/* ====================================================
# Copyright (C)2019 All rights reserved.
#
# Author : domchan
# Email : 814172254@qq.com
# File Name : root.go
# Created : 2019-01-30 10:05:09
# Describe :
#
# ====================================================*/
package cmd
import (
"crypto/tls"
"fmt"
"github.com/hiruok/etcd-cli/pkg/tls"
"github.com/patrickmn/go-cache"
"time"
"github.com/hiruok/etcd-cli/pkg/store"
"github.com/hiruok/etcd-cli/pkg/store/etcd"
)
// Root 获取etcd的客户端
type Root struct {
s store.Store
dirCache *cache.Cache
}
type Config struct {
Host string
Port int32
Ca string
Cert string
Key string
Username string
Password string
}
// NewRoot 根据输入参数获取etcd客户端
func NewRoot(cfg Config) (*Root, error) {
var t *tls.Config
if cfg.Ca != "" && cfg.Cert != "" && cfg.Key != "" {
var err error
t, err = tlsclient.Config(tlsclient.Options{
CAFile: cfg.Ca,
CertFile: cfg.Cert,
KeyFile: cfg.Key,
})
if err != nil {
return nil, err
}
}
e, err := etcdstore.New([]string{fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)}, &store.Config{
TLS: t,
ConnectionTimeout: 10 * time.Second,
Username: cfg.Username,
Password: cfg.Password,
})
if err != nil {
return nil, err
}
r := &Root{
s: e,
dirCache: cache.New(time.Second*3, time.Second*10),
}
return r, nil
}
// Close 关闭连接
func (r *Root) Close() error {
if r.s != nil {
return r.s.Close()
}
return nil
}
func (r *Root) CleanCache() {
r.dirCache.Flush()
}