SpringBoot集成Elasticsearch過程實例
1. 準備工作
需要提前安裝好Elasticsearch,訪問地址:http://127.0.0.1:9200/ 得到以下結(jié)果,得到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創(chuàng)建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服務(wù)版本是有兼容性問題的。
目前并不支持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注解,參數(shù)indexName是索引名稱,type是type名稱。
// 聲明索引名稱,type名稱@Document(indexName = "houseindex", type = "house") public class HouseIndexTemplate { @Id private Long id; private String name; ...... }
訪問接口。使用@Repository注解,并繼承ElasticsearchRepository接口,就可以直接訪問的。
有兩個參數(shù):1.返回的對象,2.ID參數(shù)數(shù)據(jù)類型
@Repository public 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}]]
原因:這是說配置的節(jié)點不可用,原因答題有3種可能:(1)IP地址或端口填寫有誤;(2)cluster_name填寫有誤;(3)Elasticsearch服務(wù)已關(guān)閉
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
logback ThresholdFilter臨界值日志過濾器源碼解讀
這篇文章主要為大家介紹了logback ThresholdFilter臨界值日志過濾器源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11Java 判斷字符串a(chǎn)和b是否互為旋轉(zhuǎn)詞
本篇文章主要介紹了判斷字符串a(chǎn)和b是否互為旋轉(zhuǎn)詞的相關(guān)知識,具有很好的參考價值。下面跟著小編一起來看下吧2017-05-05springcloud整合到項目中無法啟動報錯Failed to start bean&n
這篇文章主要介紹了springcloud整合到項目中無法啟動報錯Failed to start bean 'eurekaAutoServiceRegistration'問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01java數(shù)據(jù)庫連接池新手入門一篇就夠了,太簡單了!
數(shù)據(jù)庫連接池負責分配、管理和釋放數(shù)據(jù)庫連接,釋放空閑時間超過最大空閑時間的數(shù)據(jù)庫連接來避免因為沒有釋放數(shù)據(jù)庫連接而引起的數(shù)據(jù)庫連接遺漏,這項技術(shù)能明顯提高對數(shù)據(jù)庫操作的性能2021-06-06java ReentrantLock條件鎖實現(xiàn)原理示例詳解
這篇文章主要為大家介紹了java ReentrantLock條件鎖實現(xiàn)原理示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01