• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

SpringBoot集成Elasticsearch过程实例

springboot 搞代码 4年前 (2022-01-05) 32次浏览 已收录 0个评论

这篇文章主要介绍了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文件

  org.springframework.bootspring-boot-parent2.1.6.RELEASE  org.springframework.bootspring-boot-starter-data-elasticsearch

  注意: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: elastic<mark style="color:transparent">来源gaodaimacom搞#^代%!码网</mark>search: 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参数数据类型

 @Repository public interface HouseRepository extends ElasticsearchRepository { }

  测试用例

 @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服务已关闭

以上就是SpringBoot集成Elasticsearch过程实例的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:SpringBoot集成Elasticsearch过程实例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址