RestClient在每个请求上创建一个不是一个好习惯。您应该通过如下所示的配置bean创建一个实例:
@Configurationpublic 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(); }}然后,在您的
SearchController类中,您可以像这样注入它(并且还添加了一个清理方法,以
restClient在容器关闭时关闭实例):
@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); } }}


