SpringBoot集成Elasticsearch過程實例
1. 準備工作
需要提前安裝好Elasticsearch,訪問地址:http://127.0.0.1:9200/ 得到以下結果,得到cluster_name,下面配置使用。
{ 'name' : 'O8GslS3', 'cluster_name' : 'docker-cluster', 'cluster_uuid' : 'pviTqfXtR3GtnxF-Po-_aA', 'version' : { 'number' : '6.5.0', ...... }, 'tagline' : 'You Know, for Search'}
2. 使用Maven創建SpringBoot工程
配置Maven的pom.xml文件
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-parent</artifactId> <version>2.1.6.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> </dependencies>
注意:spring-boot-starter-data-elasticsearch包,引用的是spring-data-elasticsearch包,而spring-data-elasticsearch包的版本與elasticsearch服務版本是有兼容性問題的。
目前并不支持elasticsearch7.x,參考:https://github.com/spring-projects/spring-data-elasticsearch
配置application.yml文件
spring: data: elasticsearch: cluster-name: docker-cluster cluster-nodes: 127.0.0.1:9300 repositories: enabled: true
3. 代碼
實體類。使用@Document注解,參數indexName是索引名稱,type是type名稱。
// 聲明索引名稱,type名稱@Document(indexName = 'houseindex', type = 'house')public class HouseIndexTemplate { @Id private Long id; private String name; ......}
訪問接口。使用@Repository注解,并繼承ElasticsearchRepository接口,就可以直接訪問的。
有兩個參數:1.返回的對象,2.ID參數數據類型
@Repositorypublic interface HouseRepository extends ElasticsearchRepository<HouseIndexTemplate, Long> {}
測試用例
@RunWith(SpringRunner.class)@SpringBootTest(classes = Application.class)public class UserServiceTest { @Autowired private HouseRepository houseRepository; @Test public void selectUser(){ HouseIndexTemplate template = new HouseIndexTemplate(); template.setId(1); template.setName('Tom'); houseRepository.save(template); }}
4. 異常解釋
問題1: NoNodeAvailableException[None of the configured nodes are available: [{#transport#-1}{IVH9QII0QrOU9GkXdsJPiA}{127.0.0.1}{127.0.0.1:9300}]]
原因:這是說配置的節點不可用,原因答題有3種可能:(1)IP地址或端口填寫有誤;(2)cluster_name填寫有誤;(3)Elasticsearch服務已關閉
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. IntelliJ IDEA創建web項目的方法2. CentOS郵件服務器搭建系列—— POP / IMAP 服務器的構建( Dovecot )3. ASP中實現字符部位類似.NET里String對象的PadLeft和PadRight函數4. django創建css文件夾的具體方法5. 存儲于xml中需要的HTML轉義代碼6. Android打包上傳AAR文件到Maven倉庫的示例7. .NET SkiaSharp 生成二維碼驗證碼及指定區域截取方法實現8. MyBatis JdbcType 與Oracle、MySql數據類型對應關系說明9. phpstudy apache開啟ssi使用詳解10. jsp網頁實現貪吃蛇小游戲
