spring boot 集成 elasticsearch
1. Add maven dependency to pom
<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. Configure elasticsearch address
elasticsearch.addr=xxx.xxx.xxx.156:9300,xxx.xxx.xxx.157:9300,xxx.xxx.xxx.158:9300
3. Add bean and initialize es instance
The role of destroy-method="close" is to put the connection back into the data pool when the database connection is not in use, so that it is convenient to use it next time
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. Just inject and use
@Autowired
private RestHighLevelClient restHighLevelClient;