连接超时设置
public static RestHighLevelClient createClient(String serverHosts, Map<String, String> headers, String username, String password, int esSocketTimeout, int esConnectTimeout) {
RestClientBuilder builder = RestClient.builder(getNodes(serverHosts));
if (!headers.isEmpty()) {
List<Header> defaultHeaders = new ArrayList<>();
headers.forEach((k, v) -> {
defaultHeaders.add(new BasicHeader(k, v));
});
builder.setDefaultHeaders(defaultHeaders.toArray(new Header[defaultHeaders.size()]));
}
if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "password"));
builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
}
System.out.println("esSocketTimeout:" + esSocketTimeout);
System.out.println("esConnectTimeout:" + esConnectTimeout);
builder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
.setSocketTimeout(esSocketTimeout)
.setConnectTimeout(esConnectTimeout));
return new RestHighLevelClient(builder);
}
如何验证超时时间是否生效
Elasticsearch本质是通过http调用,在没法设置Es服务响应时间的情况下,可以自己起一个http服务作为测试桩,刻意拉长响应时间,看超时时间是否生效。
http服务
@RestController
public class TestController {
@RequestMapping(value = "/index-dataform", method = RequestMethod.HEAD)
public Object test() throws InterruptedException {
Thread.sleep(60000);
return "ok";
}
}
测试代码
public static boolean isIndexExist(RestHighLevelClient client, String indexName) throws Exception {
GetIndexRequest existsRequest = new GetIndexRequest();
existsRequest.indices(indexName);
boolean exists = client.indices().exists(existsRequest, RequestOptions.DEFAULT);
return exists;
}
@Test
public void test() throws Exception {
RestHighLevelClient client = EsClient.createClient("localhost:8082", new HashMap<>(), null, null, 10, 1000);
System.out.println(EsClient.isIndexExist(client, "index-dataform"));
EsClient.closeClient(client);
}