SpringBoot集成Elasticsearch过程实例
作者:闲人鹤 时间:2022-07-30 20:08:56
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参数数据类型
@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}]]
原因:这是说配置的节点不可用,原因答题有3种可能:(1)IP地址或端口填写有误;(2)cluster_name填写有误;(3)Elasticsearch服务已关闭
来源:https://www.cnblogs.com/huanshilang/p/12622356.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Spring boot如何集成kaptcha并生成验证码
![](https://img.aspxhome.com/file/2023/8/64918_0s.png)
Spring Cloud Gateway整合sentinel 实现流控熔断的问题
![](https://img.aspxhome.com/file/2023/7/60407_0s.png)
实例解析Java中的构造器初始化
详解Java中的线程池
![](https://img.aspxhome.com/file/2023/9/59369_0s.png)
Java面试题冲刺第十六天--消息队列
![](https://img.aspxhome.com/file/2023/0/69090_0s.png)
JAVA得到数组中最大值和最小值的简单实例
SpringBoot登录验证码实现过程详解
![](https://img.aspxhome.com/file/2023/1/64941_0s.png)
Java压缩文件ZIP实例代码
一篇文章超详细的介绍Java继承
java插入排序 Insert sort实例
Spring中的aware接口详情
![](https://img.aspxhome.com/file/2023/9/60689_0s.webp)
Java ArrayList源码深入分析
![](https://img.aspxhome.com/file/2023/8/60918_0s.png)
SpringBoot中自定义注解实现参数非空校验的示例
![](https://img.aspxhome.com/file/2023/0/70260_0s.webp)
详解Java单元测试之Junit框架使用教程
![](https://img.aspxhome.com/file/2023/8/61788_0s.png)