閱讀文本大概須要3分鐘。html
SpringBoot自帶的ES模板,不建議使用,建議使用Rest Client。若是業務簡單,且無特殊要求,能夠使用SpringBoot的模板ElasticsearchRepository來搞定。ElasticsearchRepository:java
優勢:簡單,SpringBoot無縫對接,配置簡單程序員
缺點:基於即將廢棄的TransportClient, 不能支持複雜的業務web
0x01:建立SpringBoot項目apache
建議使用 JDK使用1.8 由於Elasticsearch 的Java High Level REST Client 對java的版本要求是1.8。具體能夠參考:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-maven.html服務器
0x02:添加Rest Client依賴,並增長配置微信
<!-- 工具類 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<!-- Java Low Level REST Client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>6.3.2</version>
</dependency>
<!-- Java High Level REST Client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.3.2</version>
</dependency>
版本號請根據安裝的ES服務器版本選擇,由於ES 5.x和ES 6.x的API有差異架構
0x03:編寫單例Rest Low Level Client 和Rest High Level Client的Beanapp
@Configuration
public class ElasticsearchRestClient {
private static Logger logger = LoggerFactory.getLogger(ElasticsearchRestClient .class);
private static final int ADDRESS_LENGTH = 2;
private static final String HTTP_SCHEME = "http";
/**
* 使用冒號隔開ip和端口
*/
@Value("${elasticsearch.ip}")
String[] ipAddress;
@Bean
public RestClientBuilder restClientBuilder() {
HttpHost[] hosts = Arrays.stream(ipAddress)
.map(this::makeHttpHost)
.filter(Objects::nonNull)
.toArray(HttpHost[]::new);
log.debug("hosts:{}", Arrays.toString(hosts));
return RestClient.builder(hosts);
}
@Bean(name = "highLevelClient")
public RestHighLevelClient highLevelClient(@Autowired RestClientBuilder restClientBuilder) {
restClientBuilder.setMaxRetryTimeoutMillis(60000);
return new RestHighLevelClient(restClientBuilder);
}
private HttpHost makeHttpHost(String s) {
assert StringUtils.isNotEmpty(s);
String[] address = s.split(":");
if (address.length == ADDRESS_LENGTH) {
String ip = address[0];
int port = Integer.parseInt(address[1]);
return new HttpHost(ip, port, HTTP_SCHEME);
} else {
return null;
}
}
}
0x04: 業務使用
elasticsearch
業務Bean就能夠使用以下代碼引入ES操做類,進行相關操做。如創建索引、查詢索引、更新索引等
@Autowired
private RestHighLevelClient highLevelClient;
參考:https://www.jianshu.com/p/0b4f5e41405e
☆
往期精彩
☆
關注我
天天進步一點點
本文分享自微信公衆號 - JAVA樂園(happyhuangjinjin88)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。