springboot elasticsearch 集成
添加依赖spring-boot-starter-data-elasticsearch
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
spring-boot-starter-web是为测试使用。
添加es连接配置
spring:
elasticsearch:
rest:
uris: http://localhost:9200
username: elastic
password: 888888
然后可以直接使用RestHighLevelClient对象,spring已经生成对应bean实例。
建一个测试controller
@Resource
private RestHighLevelClient restHighLevelClient;
@RequestMapping("/get/{id}")
public @ResponseBody String get(@PathVariable("id") String id) throws IOException {
GetRequest request = new GetRequest("test",id);
GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
if(response.isExists()){
return JSON.toJSONString(response.getSourceAsMap());
}else{
return "not exists";
}
}
访问测试地址验证。
也可自定义client bean实例化方式。
@Configuration
public class RestClientConfig extends AbstractElasticsearchConfiguration {
@Override
@Bean
public RestHighLevelClient elasticsearchClient() {
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost",9200,"http"));
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic","888888"));
builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> {
httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
return httpAsyncClientBuilder;
});
return new RestHighLevelClient(builder);
}
}