springboot集成spring-boot-starter-data-elasticsearch
首先引入elasticsearch依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
然后在application配置文件中配置elasticsearch节点和集群名称相关信息
这个endpoints必配,其他根据自己实际配置 spring.data.elasticsearch.client.reactive.endpoints=150.158.6.143:9200 spring.data.elasticsearch.client.reactive.connection-timeout=3000 spring.data.elasticsearch.client.reactive.max-in-memory-size= spring.data.elasticsearch.client.reactive.password= spring.data.elasticsearch.client.reactive.username=
之后使用通用的Spring Data Repositories,我们可以使用简单的CrudRepository接口,不过这里面没有分页和排序的功能,为了拥有这些功能我们可以使用他的子接口PagingAndSortingRepository。这些接口都有两个参数需要指定一个是操作实体,另一个是实体中的主键类型,该主键需用@Id注解标注,具体参考如下:
public interface UserDao extends PagingAndSortingRepository<User,Integer> { /** * PagingAndSortingRepository<User,Integer> * CrudRepository<User,Integer> * 第一个参数为文档名称,第二个参数为ID主键类型 */ } @Data @Document(indexName = "es") public class User { @Id private Integer id; private String name; private String sex; private Integer age; private String address; } 最后就是在我们要用到的地方注入操作对象就行 @Autowired private UserDao userDao;
在完成上面的步骤之后,由于我们并没有将UserDao类注入IOC容器,所以我们可以使用注解 @EnableElasticsearchRepositories(basePackages = "com.example.esdemo.dao") 指定扫描路径,有点类似@ComponentScan,其实我们也可以在每个操作类上添加@Repository
更多细节请参考官网
上一篇:
IDEA上Java项目控制台中文乱码