Am using a Spring Boot 1.5.4.RELEASE Microservice to connect to an ElasticSearch 5.5.0 instance using the low level Rest Client that ElasticSearch provides.
pom.xml<
It's is not a good practice to create a RestClient
on every single request. You should create a single instance via a configuration bean like the one below:
@Configuration
public class ElasticsearchConfig {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port}")
private int port;
@Bean
public RestClient restClient() {
return RestClient.builder(new HttpHost(host, port))
.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
@Override
public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
return requestConfigBuilder.setConnectTimeout(5000).setSocketTimeout(60000);
}
}).setMaxRetryTimeoutMillis(60000).build();
}
}
And then in your SearchController
class you can inject it like this (and also add a cleanup method to close the restClient
instance when your container goes down):
@RestController
@RequestMapping("/api/v1")
public class SearchController {
@Autowired
private RestClient restClient;
@RequestMapping(value = "/search", method = RequestMethod.GET, produces="application/json" )
public ResponseEntity<Object> getSearchQueryResults(@RequestParam(value = "criteria") String criteria) throws IOException {
// Setup HTTP Headers
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
// Setup query and send and return ResponseEntity...
Response response = this.restClient.performRequest(...);
}
@PreDestroy
public void cleanup() {
try {
logger.info("Closing the ES REST client");
this.restClient.close();
} catch (IOException ioe) {
logger.error("Problem occurred when closing the ES REST client", ioe);
}
}
}