Files

83 lines
1.4 KiB
Go
Raw Normal View History

2021-10-15 17:31:23 +08:00
package es
2021-12-09 16:17:23 +08:00
import (
2021-12-22 14:11:14 +08:00
"context"
"github.com/olivere/elastic/v7"
2021-12-09 16:17:23 +08:00
)
2021-10-15 17:31:23 +08:00
2021-12-09 16:17:23 +08:00
type Instance struct {
2021-12-22 14:11:14 +08:00
client *elastic.Client
2021-10-15 17:31:23 +08:00
2021-12-09 16:17:23 +08:00
address []string
username, password string
2021-12-22 14:11:14 +08:00
logger elastic.Logger
2021-10-15 17:31:23 +08:00
}
2021-12-09 16:17:23 +08:00
type Option func(*Instance)
2021-10-15 17:31:23 +08:00
2021-12-09 16:17:23 +08:00
var (
2021-12-22 14:11:14 +08:00
client *elastic.Client
2021-12-09 16:17:23 +08:00
)
2021-10-15 17:31:23 +08:00
2021-12-09 16:17:23 +08:00
func WithEsAddress(address []string) Option {
return func(instance *Instance) {
instance.address = address
}
}
func WithEsUsername(username string) Option {
return func(instance *Instance) {
instance.username = username
}
}
func WithEsPassword(password string) Option {
return func(instance *Instance) {
instance.password = password
}
}
2021-12-22 14:11:14 +08:00
func WithEsLog(logger elastic.Logger) Option {
return func(instance *Instance) {
instance.logger = logger
2021-12-09 16:17:23 +08:00
}
2021-12-22 14:11:14 +08:00
}
2021-12-09 16:17:23 +08:00
2021-12-22 14:11:14 +08:00
func (this *Instance) Init() *Instance {
client, err := elastic.NewClient(
elastic.SetSniff(false),
elastic.SetURL(this.address...),
//elastic.SetInfoLog(this.logger),
)
2021-12-09 16:17:23 +08:00
if err != nil {
2021-12-22 14:11:14 +08:00
panic(err)
2021-10-15 17:31:23 +08:00
}
2021-12-22 14:11:14 +08:00
ctx := context.Background()
2021-10-15 17:31:23 +08:00
2021-12-22 14:11:14 +08:00
for _, address := range this.address {
if _, _, err = client.Ping(address).Do(ctx); err != nil {
panic(err)
}
2021-10-15 17:31:23 +08:00
}
2021-12-09 16:17:23 +08:00
this.client = client
return this
}
func (this *Instance) Local() *Instance {
client = this.client
return this
2021-10-15 17:31:23 +08:00
}
2021-12-09 16:17:23 +08:00
func NewInstance(option ...Option) *Instance {
instance := new(Instance)
for _, v := range option {
v(instance)
2021-10-15 17:31:23 +08:00
}
2021-12-09 16:17:23 +08:00
return instance
2021-10-15 17:31:23 +08:00
}
2021-12-22 14:11:14 +08:00
func GetInstance() *elastic.Client {
return client
}