spring 通过url 用户 密码 初始化ElasticSearch RestHighLevelClient

@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);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值