52 lines
1.0 KiB
Go
52 lines
1.0 KiB
Go
package es
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/elastic/go-elasticsearch/v8"
|
|
)
|
|
|
|
// ESClient 封装 Elasticsearch 客户端
|
|
type ESClient struct {
|
|
Client *elasticsearch.Client
|
|
}
|
|
|
|
// NewESClient 初始化客户端
|
|
func NewESClient(addresses []string, username, password string) (*ESClient, error) {
|
|
|
|
cfg := elasticsearch.Config{
|
|
Addresses: addresses,
|
|
Username: username,
|
|
Password: password,
|
|
Transport: &http.Transport{
|
|
TLSClientConfig: &tls.Config{
|
|
InsecureSkipVerify: true,
|
|
},
|
|
MaxIdleConnsPerHost: 100,
|
|
ResponseHeaderTimeout: 60 * time.Second,
|
|
},
|
|
CompressRequestBody: true,
|
|
}
|
|
|
|
client, err := elasticsearch.NewClient(cfg)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("创建 ES 客户端失败: %v", err)
|
|
}
|
|
|
|
res, err := client.Info()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("ES 连接失败: %v", err)
|
|
}
|
|
defer res.Body.Close()
|
|
|
|
if res.IsError() {
|
|
return nil, fmt.Errorf("ES 返回错误: %s", res.String())
|
|
}
|
|
|
|
fmt.Println("✅ Elasticsearch 连接成功")
|
|
return &ESClient{Client: client}, nil
|
|
}
|