【Elastic】SpringBoot快速集成ES

举报
程序员小明 发表于 2021/02/07 10:05:18 2021/02/07
【摘要】 Elastic Search 的底层是开源库 Lucene。但是Lucene的使用门槛比较高,必须自己写代码去调用它的接口。而Elastic Search的出现正是为了解决了这个问题,它是 Lucene 的封装,提供了 REST API 的操作接口,我们可以开箱即用。

【Elastic】SpringBoot快速集成ES

Elastic Search 的底层是开源库 Lucene。但是Lucene的使用门槛比较高,必须自己写代码去调用它的接口。而Elastic Search的出现正是为了解决了这个问题,它是 Lucene 的封装,提供了 REST API 的操作接口,我们可以开箱即用。

环境

  • JDK版本:8
  • SpringBoot:2.x
  • ES版本:7.1.1

    依赖

        <!--   集成es client,并排除低版本依赖(5.6)     -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.1.1</version>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch</groupId>
                    <artifactId>elasticsearch</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.elasticsearch.client</groupId>
                    <artifactId>elasticsearch-rest-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>7.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.1.1</version>
        </dependency>
    

    配置

    使用配置类配置,可以参考如下所示:
    先创建一个builder,用于初始化ES client

    public class EsClientBuilder {
    private int connectTimeoutMillis = 1000;
    private int socketTimeoutMillis = 30000;
    private int connectionRequestTimeoutMillis = 500;
    private int maxConnectPerRoute = 10;
    private int maxConnectTotal = 30;
    private final List<HttpHost> httpHosts;
    private EsClientBuilder(List<HttpHost> httpHosts) {
        this.httpHosts = httpHosts;
    }
    public EsClientBuilder setConnectTimeoutMillis(int connectTimeoutMillis) {
        this.connectTimeoutMillis = connectTimeoutMillis;
        return this;
    }
    public EsClientBuilder setSocketTimeoutMillis(int socketTimeoutMillis) {
        this.socketTimeoutMillis = socketTimeoutMillis;
        return this;
    }
    public EsClientBuilder setConnectionRequestTimeoutMillis(int connectionRequestTimeoutMillis) {
        this.connectionRequestTimeoutMillis = connectionRequestTimeoutMillis;
        return this;
    }
    public EsClientBuilder setMaxConnectPerRoute(int maxConnectPerRoute) {
        this.maxConnectPerRoute = maxConnectPerRoute;
        return this;
    }
    public EsClientBuilder setMaxConnectTotal(int maxConnectTotal) {
        this.maxConnectTotal = maxConnectTotal;
        return this;
    }
    public static EsClientBuilder build(List<HttpHost> httpHosts) {
        return new EsClientBuilder(httpHosts);
    }
    public RestHighLevelClient create() {
        HttpHost[] httpHostArr = httpHosts.toArray(new HttpHost[0]);
        RestClientBuilder builder = RestClient.builder(httpHostArr);
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(connectTimeoutMillis);
            requestConfigBuilder.setSocketTimeout(socketTimeoutMillis);
            requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeoutMillis);
            return requestConfigBuilder;
        });
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(maxConnectTotal);
            httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
            return httpClientBuilder;
        });
        return new RestHighLevelClient(builder);
    }
    }
    

    再交给spring容器管理:

    @Configuration
    public class ESConfig {
    @Value("${elasticsearch.nodes}")
    private List<String> nodes;
    @Value("${elasticsearch.schema}")
    private String schema;
    @Value("${elasticsearch.max-connect-total}")
    private Integer maxConnectTotal;
    @Value("${elasticsearch.max-connect-per-route}")
    private Integer maxConnectPerRoute;
    @Value("${elasticsearch.connection-request-timeout-millis}")
    private Integer connectionRequestTimeoutMillis;
    @Value("${elasticsearch.socket-timeout-millis}")
    private Integer socketTimeoutMillis;
    @Value("${elasticsearch.connect-timeout-millis}")
    private Integer connectTimeoutMillis;
    @Bean
    public RestHighLevelClient getRestHighLevelClient() {
        List<HttpHost> httpHosts = new ArrayList<>();
        for (String node : nodes) {
            try {
                String[] parts = StringUtils.split(node, ":");
                Assert.notNull(parts,"Must defined");
                Assert.state(parts.length == 2, "Must be defined as 'host:port'");
                httpHosts.add(new HttpHost(parts[0], Integer.parseInt(parts[1]), schema));
            } catch (RuntimeException ex) {
                throw new IllegalStateException(
                        "Invalid ES nodes " + "property '" + node + "'", ex);
            }
        }
        return EsClientBuilder.build(httpHosts)
                .setConnectionRequestTimeoutMillis(connectionRequestTimeoutMillis)
                .setConnectTimeoutMillis(connectTimeoutMillis)
                .setSocketTimeoutMillis(socketTimeoutMillis)
                .setMaxConnectTotal(maxConnectTotal)
                .setMaxConnectPerRoute(maxConnectPerRoute)
                .create();
    }
    }
    

    再配置一下常用的配置:

    #配置es
    elasticsearch:
    #  如果是cluster,application.yml的nodes设置多个ip:host逗号隔开即可。
    nodes: 127.0.0.1:9200
    schema: http
    max-connect-total: 50
    max-connect-per-route: 10
    connection-request-timeout-millis: 500
    socket-timeout-millis: 30000
    connect-timeout-millis: 1000
    

    使用

    接下来我们测试一下配置是否生效,一个简单的验证送给大家,如下所示:

    @Autowired
    private RestHighLevelClient client;
    @Test
    public void test() throws IOException {
        MainResponse info = client.info(RequestOptions.DEFAULT);
        System.out.println(info.toString());
    }
    

    配置生效的话,就会返回Elastic Search的配置信息:包含当前节点、集群、版本等信息。
    SpringBoot集成ES至此结束。

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。