@Configuration
public class ElasticSearchConfig {
/**
* 连接超时时间
*/
final static int connectTimeOut = 2000;
/**
* 连接超时时间
*/
final static int socketTimeOut = 30000;
/**
* 获取连接的超时时间
*/
final static int connectionRequestTimeOut = 1000;
/**
* 最大连接数
*/
final static int maxConnectNum = 200;
/**
* 最大路由连接数
*/
final static int maxConnectPerRoute = 200;
@Value("${elasticsearch.username}")
String username;
@Value("${elasticsearch.password}")
String password;
@Value("${elasticsearch.url}")
String url;
@Bean(name = "restHighLevelClient")
public RestHighLevelClient client() {
RestClientBuilder builder = null;
try {
URL urll = new URL(this.url);
HttpHost httpHost = new HttpHost(urll.getHost(), urll.getPort(), urll.getProtocol());
System.out.println(urll.getHost() + urll.getPort() + urll.getProtocol());
builder = RestClient.builder(httpHost);
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(username, password));
builder.setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.disableAuthCaching();
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
});
// 异步httpclient连接延时配置
builder.setRequestConfigCallback(requestConfigBuilder -> {
requestConfigBuilder.setConnectTimeout(connectTimeOut);
requestConfigBuilder.setSocketTimeout(socketTimeOut);
requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
return requestConfigBuilder;
});
// 异步httpclient连接数配置
builder.setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.setMaxConnTotal(maxConnectNum);
httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
});
} catch (MalformedURLException e) {
e.printStackTrace();
}
return new RestHighLevelClient(builder);
}
}
spring 通过url 用户 密码 初始化ElasticSearch RestHighLevelClient
最新推荐文章于 2023-05-30 13:37:37 发布