「Elasticsearch」SpringBoot快速集成ES
小明 Lv6

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

环境

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

    依赖

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    <!--   集成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
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    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容器管理:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    @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();
    }
    }
    再配置一下常用的配置:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    #配置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

    使用

    接下来我们测试一下配置是否生效,一个简单的验证送给大家,如下所示:
    1
    2
    3
    4
    5
    6
    7
    @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至此结束。
 评论