config.yml
elasticsearch:
enable: true
url: http://192.168.217.142:9200
sniff: false #将返回的url 作为请求的路径
healthcheckInterval: 5s
index-prefix: gva
新增配置结构体
config/elasticsearch.go
type ElasticSearch struct {
Enable bool `mapstructure:"enable" json:"enable" yaml:"enable"`
URL string `mapstructure:"url" json:"url" yaml:"url"`
Sniff bool `mapstructure:"sniff" json:"sniff" yaml:"sniff"`
HealthcheckInterval time.Duration `mapstructure:"healthcheckInterval" json:"healthcheckInterval" yaml:"healthcheckInterval"`
IndexPrefix string `mapstructure:"index-prefix" json:"index-prefix" yaml:"index-prefix"`
// mapstructure 将通用的map[string]interface{} 解码到对应的结构体中
}
嵌入主配置
config/config.go
ElasticSearch ElasticSearch `mapstructure:"elasticsearch" json:"elasticsearch" yaml:"elasticsearch"`
定义全局配置
GVA_ELASTIC *elastic.Client
创建客户端
func InitES() {
elasticConfig := global.GVA_CONFIG.ElasticSearch
if elasticConfig.Enable {
fmt.Printf("elasticsearch: %v\n", elasticConfig)
client, err := elastic.NewClient(
elastic.SetURL(elasticConfig.URL),
elastic.SetSniff(elasticConfig.Sniff),
elastic.SetHealthcheckInterval(elasticConfig.HealthcheckInterval),
)
if err != nil {
global.GVA_LOG.Error("创建ElasticSearch 客户端错误", zap.Error(err))
}
global.GVA_ELASTIC = client
}
}
创建控制器 实现简单的ES查询
api/system/sys_elasticsearch.go
const indexName = "test" # 对应的es中的索引
func (b *BaseApi) SearchById(c *gin.Context) {
id, _ := c.GetQuery("id")
res, err := global.GVA_ELASTIC.Get().Index(indexName).Type("_doc").Id(id).Do(c)
if err != nil {
response.FailWithMessage("查询失败", c)
}
response.OkWithDetailed(res.Source, "查询到的记录", c)
}
注册路由
router/sys_elastic.go
type ElasticRouter struct {
}
func (s *ElasticRouter) ElasticOpsRouter(Router *gin.RouterGroup) {
EsRouter := Router.Group("es").Use(middleware.OperationRecord())
var baseApi = v1.ApiGroupApp.SystemApiGroup.BaseApi
{
EsRouter.GET("searchById", baseApi.SearchById) //
}
}
继承到入口函数 加载到main的启动中
initialize.InitES() // 初始化ElasticSearch
请求测试结果