本文主要研究一下springboot elasticsearch healthIndicator

ElasticsearchHealthIndicatorProperties

spring-boot-actuator-autoconfigure-2.1.4.RELEASE-sources.jar!/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticsearchHealthIndicatorProperties.java

@ConfigurationProperties(prefix = "management.health.elasticsearch",ignoreUnknownFields = false)
public class ElasticsearchHealthIndicatorProperties {/*** Comma-separated index names.*/private List<String> indices = new ArrayList<>();/*** Time to wait for a response from the cluster.*/private Duration responseTimeout = Duration.ofMillis(100);public List<String> getIndices() {return this.indices;}public void setIndices(List<String> indices) {this.indices = indices;}public Duration getResponseTimeout() {return this.responseTimeout;}public void setResponseTimeout(Duration responseTimeout) {this.responseTimeout = responseTimeout;}}
复制代码
  • ElasticsearchHealthIndicatorProperties提供了indices,responseTimeout两个配置项

ElasticSearchClientHealthIndicatorAutoConfiguration

spring-boot-actuator-autoconfigure-2.1.4.RELEASE-sources.jar!/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchClientHealthIndicatorAutoConfiguration.java

@Configuration
@ConditionalOnClass(Client.class)
@ConditionalOnBean(Client.class)
@ConditionalOnEnabledHealthIndicator("elasticsearch")
@AutoConfigureBefore(HealthIndicatorAutoConfiguration.class)
@AutoConfigureAfter(ElasticsearchAutoConfiguration.class)
@EnableConfigurationProperties(ElasticsearchHealthIndicatorProperties.class)
public class ElasticSearchClientHealthIndicatorAutoConfiguration extendsCompositeHealthIndicatorConfiguration<ElasticsearchHealthIndicator, Client> {private final Map<String, Client> clients;private final ElasticsearchHealthIndicatorProperties properties;public ElasticSearchClientHealthIndicatorAutoConfiguration(Map<String, Client> clients,ElasticsearchHealthIndicatorProperties properties) {this.clients = clients;this.properties = properties;}@Bean@ConditionalOnMissingBean(name = "elasticsearchHealthIndicator")public HealthIndicator elasticsearchHealthIndicator() {return createHealthIndicator(this.clients);}@Overrideprotected ElasticsearchHealthIndicator createHealthIndicator(Client client) {Duration responseTimeout = this.properties.getResponseTimeout();return new ElasticsearchHealthIndicator(client,(responseTimeout != null) ? responseTimeout.toMillis() : 100,this.properties.getIndices());}}
复制代码
  • ElasticSearchClientHealthIndicatorAutoConfiguration创建的是ElasticsearchHealthIndicator(elasticsearch),它是通过org.elasticsearch.client.Client去检测的

ElasticsearchHealthIndicator

spring-boot-actuator-2.1.4.RELEASE-sources.jar!/org/springframework/boot/actuate/elasticsearch/ElasticsearchHealthIndicator.java

public class ElasticsearchHealthIndicator extends AbstractHealthIndicator {private static final String[] ALL_INDICES = { "_all" };private final Client client;private final String[] indices;private final long responseTimeout;/*** Create a new {@link ElasticsearchHealthIndicator} instance.* @param client the Elasticsearch client* @param responseTimeout the request timeout in milliseconds* @param indices the indices to check*/public ElasticsearchHealthIndicator(Client client, long responseTimeout,List<String> indices) {this(client, responseTimeout,(indices != null) ? StringUtils.toStringArray(indices) : null);}/*** Create a new {@link ElasticsearchHealthIndicator} instance.* @param client the Elasticsearch client* @param responseTimeout the request timeout in milliseconds* @param indices the indices to check*/public ElasticsearchHealthIndicator(Client client, long responseTimeout,String... indices) {super("Elasticsearch health check failed");this.client = client;this.responseTimeout = responseTimeout;this.indices = indices;}@Overrideprotected void doHealthCheck(Health.Builder builder) throws Exception {ClusterHealthRequest request = Requests.clusterHealthRequest(ObjectUtils.isEmpty(this.indices) ? ALL_INDICES : this.indices);ClusterHealthResponse response = this.client.admin().cluster().health(request).actionGet(this.responseTimeout);switch (response.getStatus()) {case GREEN:case YELLOW:builder.up();break;case RED:default:builder.down();break;}builder.withDetail("clusterName", response.getClusterName());builder.withDetail("numberOfNodes", response.getNumberOfNodes());builder.withDetail("numberOfDataNodes", response.getNumberOfDataNodes());builder.withDetail("activePrimaryShards", response.getActivePrimaryShards());builder.withDetail("activeShards", response.getActiveShards());builder.withDetail("relocatingShards", response.getRelocatingShards());builder.withDetail("initializingShards", response.getInitializingShards());builder.withDetail("unassignedShards", response.getUnassignedShards());}}
复制代码
  • ElasticsearchHealthIndicator继承了AbstractHealthIndicator,这里如果不指定indices的话,默认是ALL_INDICES(_all);doHealthCheck方法使用client.admin().cluster().health(request)来进行请求,之后根据ClusterHealthResponse的状态来决定是up还是down,如果是GREEN或YELLOW则返回Status.UP,如果是RED则返回Status.DOWN

ElasticSearchRestHealthIndicatorAutoConfiguration

spring-boot-actuator-autoconfigure-2.1.4.RELEASE-sources.jar!/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchRestHealthIndicatorAutoConfiguration.java

@Configuration
@ConditionalOnClass(RestClient.class)
@ConditionalOnBean(RestClient.class)
@ConditionalOnEnabledHealthIndicator("elasticsearch")
@AutoConfigureBefore(HealthIndicatorAutoConfiguration.class)
@AutoConfigureAfter({ RestClientAutoConfiguration.class,ElasticSearchClientHealthIndicatorAutoConfiguration.class })
public class ElasticSearchRestHealthIndicatorAutoConfiguration extendsCompositeHealthIndicatorConfiguration<ElasticsearchRestHealthIndicator, RestClient> {private final Map<String, RestClient> clients;public ElasticSearchRestHealthIndicatorAutoConfiguration(Map<String, RestClient> clients) {this.clients = clients;}@Bean@ConditionalOnMissingBean(name = "elasticsearchRestHealthIndicator")public HealthIndicator elasticsearchRestHealthIndicator() {return createHealthIndicator(this.clients);}@Overrideprotected ElasticsearchRestHealthIndicator createHealthIndicator(RestClient client) {return new ElasticsearchRestHealthIndicator(client);}}
复制代码
  • ElasticSearchRestHealthIndicatorAutoConfiguration创建的是ElasticsearchRestHealthIndicator(elasticsearchRest),它是通过org.elasticsearch.client.RestClient去检测的

ElasticsearchRestHealthIndicator

spring-boot-actuator-2.1.4.RELEASE-sources.jar!/org/springframework/boot/actuate/elasticsearch/ElasticsearchRestHealthIndicator.java

public class ElasticsearchRestHealthIndicator extends AbstractHealthIndicator {private static final String RED_STATUS = "red";private final RestClient client;private final JsonParser jsonParser;public ElasticsearchRestHealthIndicator(RestClient client) {super("Elasticsearch health check failed");this.client = client;this.jsonParser = JsonParserFactory.getJsonParser();}@Overrideprotected void doHealthCheck(Health.Builder builder) throws Exception {Response response = this.client.performRequest(new Request("GET", "/_cluster/health/"));StatusLine statusLine = response.getStatusLine();if (statusLine.getStatusCode() != HttpStatus.SC_OK) {builder.down();builder.withDetail("statusCode", statusLine.getStatusCode());builder.withDetail("reasonPhrase", statusLine.getReasonPhrase());return;}try (InputStream inputStream = response.getEntity().getContent()) {doHealthCheck(builder,StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8));}}private void doHealthCheck(Health.Builder builder, String json) {Map<String, Object> response = this.jsonParser.parseMap(json);String status = (String) response.get("status");if (RED_STATUS.equals(status)) {builder.outOfService();}else {builder.up();}builder.withDetails(response);}}
复制代码
  • ElasticsearchRestHealthIndicator继承了AbstractHealthIndicator,构造器通过JsonParserFactory.getJsonParser()创建了JsonParser
  • doHealthCheck方法通过RestClient.performRequest(new Request("GET", "/_cluster/health/"))进行请求,如果http response status code不是HttpStatus.SC_OK,直接返回Status.DOWN;如果是HttpStatus.SC_OK再进一步解析json判断
  • 私有的doHealthCheck方法通过jsonParser.parseMap(json)解析返回json为Map,然后取status字段,如果是red则返回Status.OUT_OF_SERVICE,否则返回Status.UP

GET /_cluster/health/在http response status code为200的情况下返回的结构实例如下:

{"cluster_name" : "docker-cluster","status" : "yellow","timed_out" : false,"number_of_nodes" : 1,"number_of_data_nodes" : 1,"active_primary_shards" : 8,"active_shards" : 8,"relocating_shards" : 0,"initializing_shards" : 0,"unassigned_shards" : 6,"delayed_unassigned_shards" : 0,"number_of_pending_tasks" : 0,"number_of_in_flight_fetch" : 0,"task_max_waiting_in_queue_millis" : 0,"active_shards_percent_as_number" : 57.14285714285714
}
复制代码

ElasticSearchJestHealthIndicatorAutoConfiguration

spring-boot-actuator-autoconfigure-2.1.4.RELEASE-sources.jar!/org/springframework/boot/actuate/autoconfigure/elasticsearch/ElasticSearchJestHealthIndicatorAutoConfiguration.java

@Configuration
@ConditionalOnClass(JestClient.class)
@ConditionalOnBean(JestClient.class)
@ConditionalOnEnabledHealthIndicator("elasticsearch")
@AutoConfigureBefore(HealthIndicatorAutoConfiguration.class)
@AutoConfigureAfter({ JestAutoConfiguration.class,ElasticSearchClientHealthIndicatorAutoConfiguration.class })
public class ElasticSearchJestHealthIndicatorAutoConfiguration extendsCompositeHealthIndicatorConfiguration<ElasticsearchJestHealthIndicator, JestClient> {private final Map<String, JestClient> clients;public ElasticSearchJestHealthIndicatorAutoConfiguration(Map<String, JestClient> clients) {this.clients = clients;}@Bean@ConditionalOnMissingBean(name = "elasticsearchHealthIndicator")public HealthIndicator elasticsearchHealthIndicator() {return createHealthIndicator(this.clients);}@Overrideprotected ElasticsearchJestHealthIndicator createHealthIndicator(JestClient client) {return new ElasticsearchJestHealthIndicator(client);}}
复制代码
  • ElasticSearchJestHealthIndicatorAutoConfiguration创建的是ElasticsearchJestHealthIndicator(elasticsearch),它是通过io.searchbox.client.JestClient去检测的

ElasticsearchJestHealthIndicator

spring-boot-actuator-2.1.4.RELEASE-sources.jar!/org/springframework/boot/actuate/elasticsearch/ElasticsearchJestHealthIndicator.java

public class ElasticsearchJestHealthIndicator extends AbstractHealthIndicator {private final JestClient jestClient;private final JsonParser jsonParser = JsonParserFactory.getJsonParser();public ElasticsearchJestHealthIndicator(JestClient jestClient) {super("Elasticsearch health check failed");this.jestClient = jestClient;}@Overrideprotected void doHealthCheck(Health.Builder builder) throws Exception {JestResult healthResult = this.jestClient.execute(new io.searchbox.cluster.Health.Builder().build());if (healthResult.getResponseCode() != 200 || !healthResult.isSucceeded()) {builder.down();builder.withDetail("statusCode", healthResult.getResponseCode());}else {Map<String, Object> response = this.jsonParser.parseMap(healthResult.getJsonString());String status = (String) response.get("status");if (status.equals(io.searchbox.cluster.Health.Status.RED.getKey())) {builder.outOfService();}else {builder.up();}builder.withDetails(response);}}}
复制代码
  • ElasticsearchJestHealthIndicator继承了AbstractHealthIndicator,构造器通过接收JestClient
  • doHealthCheck方法通过jestClient.execute(new io.searchbox.cluster.Health.Builder().build())进行请求,如果http response status code不是200,或者healthResult.isSucceeded()不是true则直接返回Status.DOWN
  • 如果http response status code是200且healthResult.isSucceeded()为true则再进一步通过jsonParser.parseMap(json)解析返回json为Map,然后取status字段,如果是io.searchbox.cluster.Health.Status.RED.getKey()则返回Status.OUT_OF_SERVICE,否则返回Status.UP

小结

  • springboot提供了三个elasticsearch的healthIndicator配置,分别是ElasticSearchClientHealthIndicatorAutoConfiguration、ElasticSearchRestHealthIndicatorAutoConfiguration、ElasticSearchJestHealthIndicatorAutoConfiguration
  • ElasticSearchClientHealthIndicatorAutoConfiguration创建的是ElasticsearchHealthIndicator(elasticsearch),它是通过org.elasticsearch.client.Client去检测的
  • ElasticSearchRestHealthIndicatorAutoConfiguration创建的是ElasticsearchRestHealthIndicator(elasticsearchRest),它是通过org.elasticsearch.client.RestClient去检测的
  • ElasticSearchJestHealthIndicatorAutoConfiguration创建的是ElasticsearchJestHealthIndicator(elasticsearch),它是通过io.searchbox.client.JestClient去检测的
  • ElasticsearchHealthIndicatorProperties提供了indices,responseTimeout两个配置项,对于使用org.elasticsearch.client.Client的如果没有配置应用使用的indices,则使用ALL_INDICES(_all)去请求;而使用org.elasticsearch.client.RestClient或io.searchbox.client.JestClient的它们请求的是/_cluster/health/这个接口

doc

  • spring-boot-actuator-autoconfigure module

转载于:https://juejin.im/post/5cb88c7bf265da03a85aba9c

聊聊springboot elasticsearch healthIndicator相关推荐

  1. springboot+elasticsearch+bboss框架集成遇到的坑

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言 一.为什么要用bboss? 二.遇到的坑 1.kibana.head页面查询结果不一致 2.head查询结果与bbos ...

  2. springboot+elasticsearch+neo4j+vue+activiti数字知识库管理系统

    文章目录 前言 一.项目概要 二.相关技术点 1.富文本编辑器 2.全文检索 3.知识图谱 4.工作流 总结 前言 在数字化高度普及的时代,企事业机关单位在日常工作中会产生大量的文档,例如医院制度汇编 ...

  3. SpringBoot Elasticsearch

    文章目录 Windwos Elasticsearch Elasticsearch 基本介绍 Elasticsearch 6.8.5 单机安装 kibana6.8.5 可视化工具 Springboot ...

  4. SpringBoot Elasticsearch组合查询封装

    最近项目组需要用到Elasticsearch,封装了ESQueryBuilder方便条件组合,结合ES工具类使用效果更佳,下面是ES工具类传送门: SpringBoot Elasticsearch工具 ...

  5. springboot ElasticSearch配置自定义转换器ElasticsearchCustomConversions

    springboot ElasticSearch配置自定义转换器ElasticsearchCustomConversions 问题场景 在将Timestamp类型存进Elasticsearc后,将其取 ...

  6. springboot + elasticsearch

    tips: 上一篇文章我们整合了springboot 与kafka,细心的童鞋可能已经发现了我们使用的springboot版本为最新的2.0.0,同样spring-kafka也为最新的版本2.1.4, ...

  7. SpringBoot ElasticSearch 全文搜索

    2019独角兽企业重金招聘Python工程师标准>>> 一.pom.xml配置 SpringBoot版本1.5.6https://blog.csdn.net/kingice1014/ ...

  8. springboot+Elasticsearch实现word,pdf,txt内容抽取并高亮分词全文检索

    文章目录 需求 一.环境 二.功能实现 1.搭建环境 2.文件内容识别 三.代码 需求 产品希望我们这边能够实现用户上传PDF,WORD,TXT之内得文本内容,然后用户可以根据附件名称或文件内容模糊查 ...

  9. SpringBoot+Elasticsearch实现过程

    前言: 最近因为工作中用到Elasticsearch,之前没接触过,所以学习了一下Elasticsearch搜索引擎,自己在本地搭建了一下过程,记录一下. 首先我查了一下springBoot版本和El ...

最新文章

  1. Linux 空格转换行
  2. mysql 织梦 索引_Mysql索引详解 建立索引的优势劣势以及索引规范
  3. Scott Mitchell的ASP.NET2.0数据指南中文版索引
  4. python 依据某几列累加求和_Python爬虫笔记:爬取单个页面
  5. 为什么SOFA RPC调用30s还不超时?
  6. 2017/Province_Java_B/4/魔方状态
  7. 【强化学习】A3C原理
  8. php substr_replace 中文乱码,php substr_replace替换字符串一些实例_PHP教程
  9. Python学习 - 之super函数
  10. 【干货】史上最全的Tensorflow学习资源汇总(转)
  11. docker pull下载很慢_一文了解Docker容器技术的操作
  12. mysql5.7应该导什么包_烘焙知识 | 不同的蛋糕,应该如何完美脱模?
  13. 交换两个数组的内容555555555
  14. 基于jsp+java+ssm的大学生缴费系统-计算机毕业设计
  15. java雷霆战机项目收获_java实习项目_雷霆战机
  16. Broadcast 使用详解
  17. HTML-坦克大战-完成子弹连发功能(三)
  18. 搭建VS2010+ACCESS2003环境遇到的问题
  19. 动画片“喜洋洋与灰太狼”和“麦兜”的营销策略
  20. 可视化智能配电房监控管理系统 助力配电房运行安全解决方案

热门文章

  1. SAP PM 初级系列19 - IP10为维修计划触发维修工单的同时也自动触发了维修通知单!
  2. SAP PM 初级系列4 - 定义功能位置的结构标识
  3. 张文宏在人工智能大会上“泼冷水”:国内疫情基本结束,防控一开始用的全是“人工”!
  4. SAP SD基础知识之税(Taxes)
  5. 2019 年ML NLP领域十大研究热点
  6. 谷歌开源 MobileNetV3:新思路 AutoML 改进计算机视觉模型移动端
  7. 从其他领域和智能机器人的联系,浅谈人工智能的前景
  8. 概率模型与条件随机场
  9. 人工智能(Artificial Intelligence)常用算法
  10. 资源丨机器学习进阶路上不可错过的28个视频