由于近期父工程SpringBoot版本升级,导致老工程的SpringBootDataElasticSearch对应的版本升级,在SpringBootAdmin中,该项目的健康检查一直失败
原来健康检查配置为
spring:
elasticsearch:
rest:
uris: [10.10.200.190:9200]
升级后为:
spring:
data:
elasticSearch:
client:
reactive:
endpoints: [10.10.200.190:9200]
担心后续再度升级会导致问题进一步加深,故移除SpringDataElasticSearch的依赖,自己定义连接配置和健康检查
ES版本为7.6.2
连接配置
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
@Getter
@Setter
public class ElasticsearchConfig {
private String[] address = new String[]{"localhost:9200"};
private int connectionTimeout = 30_000;
private int socketTimeout = 30_000;
private int connectionRequestTimeout =30_000 ;
private int maxConnTotal = 10;
private int maxConnPerRoute = 10;
@Bean
RestHighLevelClient client() {
List<HttpHost> hostList = new ArrayList<>();
for (String address : address) {
String[] split = address.split(":");
hostList.add(new HttpHost(split[0],Integer.parseInt(split[1])));
}
RestClientBuilder builder = RestClient.builder(hostList.toArray(new HttpHost[]{}));
builder.setRequestConfigCallback(requestConfigCallback->{
requestConfigCallback.setConnectTimeout(connectionTimeout);
requestConfigCallback.setSocketTimeout(socketTimeout);
requestConfigCallback.setConnectionRequestTimeout(connectionRequestTimeout);
return requestConfigCallback;
});
builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> {
httpAsyncClientBuilder.setMaxConnTotal(maxConnTotal);
httpAsyncClientBuilder.setMaxConnPerRoute(maxConnPerRoute);
return httpAsyncClientBuilder;
});
return new RestHighLevelClient(builder);
}
健康检查
@Configuration
@ConditionalOnProperty(value = "health-check",prefix = "elasticsearch",havingValue = "true")
public class ElasticsearchRestHealthIndicator extends AbstractHealthIndicator {
private static final String RED_STATUS = "red";
private final RestHighLevelClient client;
private final JsonParser jsonParser;
public ElasticsearchRestHealthIndicator(RestHighLevelClient client) {
super("Elasticsearch health check failed");
this.client = client;
this.jsonParser = JsonParserFactory.getJsonParser();
}
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
ClusterHealthRequest request = new ClusterHealthRequest();
ClusterHealthResponse response;
// 3、发送请求到ES
try {
response = client.cluster().health(request, RequestOptions.DEFAULT);
}catch (Exception e){
builder.down();
builder.withDetail("reasonPhrase", e.getMessage());
return;
}
// 4、获取健康状况
doHealthCheck(builder, response);
}
private void doHealthCheck(Health.Builder builder, ClusterHealthResponse response) {
String status = response.getStatus().name();
if (RED_STATUS.equals(status)) {
builder.outOfService();
}
else {
builder.up();
}
Map map = JsonUtil.toObj(JsonUtil.toJson(response), Map.class);
builder.withDetails(map);
}
}