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

更多细节请参考官网 https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#preface)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙茶清欢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值