阅读文本大概需要3分钟。
SpringBoot自带的ES模板,不建议使用,建议使用Rest Client。如果业务简单,且无特殊要求,可以使用SpringBoot的模板ElasticsearchRepository来搞定。ElasticsearchRepository:
优点:简单,SpringBoot无缝对接,配置简单
缺点:基于即将废弃的TransportClient, 不能支持复杂的业务
0x01:创建SpringBoot项目
建议使用 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的Bean
@Configurationpublic 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: 业务使用
业务Bean就可以使用如下代码引入ES操作类,进行相关操作。如建立索引、查询索引、更新索引等
@Autowiredprivate RestHighLevelClient highLevelClient;
参考:https://www.jianshu.com/p/0b4f5e41405e
☆
往期精彩
☆
关注我
每天进步一点点
喜欢!在看☟
本文分享自微信公众号 - JAVA乐园(happyhuangjinjin88)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。