spring boot 集成 elasticsearch

spring boot 集成 elasticsearch

1. 在pom中添加 maven 依赖

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
      <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
        </dependency>

2. 配置 elasticsearch 地址

elasticsearch.addr=xxx.xxx.xxx.156:9300,xxx.xxx.xxx.157:9300,xxx.xxx.xxx.158:9300

3. 添加bean ,初始化es 实例

destroy-method=“close” 的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class ElasticSearchConfig {
    
    

    @Value("${elasticsearch.addr}")
    private String addr;

    @Bean(destroyMethod = "close")
    public RestHighLevelClient restHighLevelClient() {
    
    

        String[] segments = addr.split(",");
        HttpHost[] esNodes = new HttpHost[segments.length];
        for (int i = 0; i < segments.length; i++) {
    
    
            String[] hostAndPort = segments[i].split(":");
            esNodes[i] = new HttpHost(hostAndPort[0], Integer.parseInt(hostAndPort[1]), "http");
        }
        return new RestHighLevelClient(RestClient.builder(esNodes));
    }
}

4. 注入使用即可

   @Autowired
    private RestHighLevelClient restHighLevelClient;

猜你喜欢

转载自blog.csdn.net/xu990128638/article/details/130187845