-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathes.go
80 lines (67 loc) · 1.36 KB
/
es.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
package utils
import (
"fmt"
"sync"
"time"
"github.com/niwho/elasticsearch"
)
const (
DateFmt = "_%d_%02d_%02d"
)
var (
TdyIndex string
IndexLock sync.RWMutex
EsClient elasticsearch.EsClientV3
// config
Hosts []string
Index string
Type string
ShardNum int
ReplicaNum int
RefreshInterval int
)
func InitEsClient(hosts []string, index, ttype string, shardNum, replicaNum, refreshInterval int) {
Hosts = hosts
Index = index
Type = ttype
ShardNum = shardNum
ReplicaNum = replicaNum
RefreshInterval = refreshInterval
var err error
EsClient, err = elasticsearch.CreateEsClientV3(Hosts)
if err != nil {
panic(err)
}
GetIndex()
}
func initEsIndex(index string) {
err := EsClient.CreateEsIndex(
index,
int32(ShardNum),
int32(ReplicaNum),
int32(RefreshInterval),
)
if err != nil {
panic(err)
}
}
func GetIndex() string {
t := time.Now()
currentIndex := Index + fmt.Sprintf(DateFmt, t.Year(), t.Month(), t.Day())
if TdyIndex != currentIndex {
IndexLock.Lock()
// 二次判断
if TdyIndex != currentIndex {
initEsIndex(currentIndex)
TdyIndex = currentIndex
}
IndexLock.Unlock()
}
return TdyIndex
}
func Insert2Es(dat string) error {
return EsClient.Insert(GetIndex(), Type, dat)
}
func Insert2EsBulk(dats []interface{}) error {
return EsClient.BulkInsert(GetIndex(), Type, dats)
}