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. idea給項目打war包的方法步驟2. Intellij IDEA 2020.3 配置教程詳解3. IntelliJ IDEA設置編碼格式的方法4. Python importlib模塊重載使用方法詳解5. 使用 kind 和 Docker 啟動本地的 Kubernetes環境6. 兩行Javascript代碼生成UUID的方法7. IntelliJ IDEA刪除類的方法步驟8. ASP基礎入門第八篇(ASP內建對象Application和Session)9. Entity Framework使用DBContext實現增刪改查10. React基礎-JSX的本質-虛擬DOM的創建過程實例分析
