首页 > 其他分享 >Spring Boot3.x集成ElasticSearch8.x

Spring Boot3.x集成ElasticSearch8.x

时间:2024-01-16 17:24:01浏览次数:24  
标签:Spring springframework id Boot3 import org size ElasticSearch8 page

Spring Boot3.x集成ElasticSearch8.x

  • 版本说明,本demo使用Spring Boot3.2.1 + JDK17 + ElasticSearch8.11.3

  • 前提是已经部署好了自己的ElasticSearch环境,我这里直接用容器默认部署好了,能访问即可

创建Spring Boot项目

  • 导入pom依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            <version>3.2.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
  • 配置文件(yml格式)
spring:
  elasticsearch:
    uris: 139.xxx.xxx.xxx:9200
  • 实体类
import lombok.Builder;
import lombok.Data;
import org.springframework.data.elasticsearch.annotations.Document;

@Data
@Builder
// 这个注解要加上,不然会报索引名必须小写,默认是类名,也就是Product
@Document(indexName = "product")
public class Product {

    private Long id;

    private String name;

    private Integer price;

    private String description;

}
  • repository
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface ProductElasticsearchRepository extends ElasticsearchRepository<Product, Long> {
	// es的条件查询通过命名会转换为条件,这里就是模糊查询名字的意思,后面是分页参数,具体的命名规则可在官方文档查看
    Iterable<Product> findByNameLike(String name, PageRequest pageRequest);
}

官方文档:Query methods :: Spring Data Elasticsearch

  • controller
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class EsController {

    @Resource
    private ProductElasticsearchRepository repository;

    @GetMapping("add/{id}")
    public Product add(@PathVariable Long id) {
        return repository.save(Product.builder()
                .id(id)
                .name("商品" + id)
                .price(99 + id.intValue())
                .description("超级简介咯咯咯" + id).build());
    }

    @GetMapping("findAll")
    public Iterable<Product> findAll() {
        return repository.findAll();
    }

    @GetMapping("findPage/{page}/{size}")
    public Iterable<Product> findPage(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        return repository.findAll(PageRequest.of(page, size, Sort.by("id").descending()));
    }

    @GetMapping("findByNameLike/{page}/{size}/{name}")
    public Iterable<Product> findByNameLike(@PathVariable("page") Integer page, @PathVariable("size") Integer size, @PathVariable("name") String name) {
        return repository.findByNameLike(name, PageRequest.of(page, size, Sort.by("id").descending()));
    }
    
}

测试

  • 调用add接口插入一些数据
http://localhost:8080/add/1

  • 然后就可以测试其他的查询方法了
http://localhost:8080/findAll

注意,分页页码默认是从0开始的

http://localhost:8080/findPage/0/5

http://localhost:8080/findByNameLike/0/5/6

  • 至于其他改删的方法就自行调用出来就好了,小demo,所以不会考虑规范性,主打一个图一乐

标签:Spring,springframework,id,Boot3,import,org,size,ElasticSearch8,page
From: https://www.cnblogs.com/ximensama/p/17968121

相关文章

  • Spring事务传播机制
    1.Spring对事物的支持一般有两种方式编程式事务管理:通过 TransactionTemplate或者TransactionManager手动管理事务,实际应用中很少使用,这不是本文的重点,就不在这里赘述。声明式事务管理:使用场景最多,也是最推荐使用的方式,直接加上@Transactional注解即可。2.Transactional注......
  • springboot~shardingsphere在非spring框架中的使用
    shardingsphere已经很方便的被springboot集成了,你只要引入sharding-jdbc-spring-boot-starter这个包就可以了,而如果是原生java的话,你就需要自己去实现了,主要是重新定义数据源,定义规则等问题,本文主要介绍原生环境下的shardingsphere的使用。依赖引用<dependencies><!--......
  • [spring] spring学习笔记(2): 通过xml实现依赖注入 - 特殊注入类型
    实际应用中,我们的对象可能会引用很多不同类型的东西,不单单只是几个数值对象类型在前一篇文章中,已经使用引用对象作为例子,关键在于使用ref<!--注意引用的对象要先创建Bean,id为weapon1--><beanid="player1"class="com.demo.player"> <!--通过setter注入,注意ref的......
  • springboot第48集:【思维导图】地图,面向对象,异常,功能代码
    在SpringBoot中,可以通过编写拦截器(Interceptor)来对请求进行拦截与处理。下面是一个简单的拦截器实现示例:创建一个类并实现HandlerInterceptor接口publicclassAuthInterceptorimplementsHandlerInterceptor{@OverridepublicbooleanpreHandle(HttpServletRequest......
  • Springboot上传文件大小限制处理
    今天在开发过程中遇到一个文件上传的问题io.undertow.server.RequestTooBigException:UT000020:Connectionterminatedasrequestwaslargerthan10485760Servlet容器使用的是undertow,看异常信息应该是默认存在10MB的文件大小限制。百度了一下,找到如下配置,问题得以解决,记......
  • Spring Cloud整体架构解析
    SpringCloud整体架构SpringCloud的中文名我们就暂且称呼它为“春云”吧,听上去是多么朴实无华的名字,不过呢一般名字起的低调的都是厉害角色,我们就看看SpringCloud都提供了哪些靠谱功能吧。SpringCloud是一款微服务架构的一站式解决方案,你在微服务化过程中碰到的任何问题,都可......
  • SpringSecurity表单认证(二)
    用户名+密码系统默认登录用户名:user密码每次服务启动后随机生成密码用户信息获取原理(数据库获取)实现该接口,security默认自动生成密码关闭。框架源码:packageorg.springframework.security.core.userdetails;publicinterfaceUserDetailsService{UserDetailsloa......
  • [spring] spring学习笔记(1): 通过xml实现依赖注入(1)
    依赖注入是spring框架中一个重要思想-InversionofControl(IoC)-的实现,大体上来说,就是通过配置Bean对象,让spring内置的方法来为主对象创建需要的依赖对象;打个比方,在java中,当我们想要使用某个类时,应当通过new关键字来指定,i.e.//在这里创建一个类,他需要使......
  • Spring 工具:DigestUtils md5 摘要工具
    工具类:org.springframework.util.DigestUtils作用:计算字节数组、输入流的md5摘要所在模块:spring-core方法描述Stringmd5DigestAsHex(byte[]bytes)返回字节数组的md5摘要(计算字符串)Stringmd5DigestAsHex(InputStreaminputStream)返回输入流的md5......
  • Spring 工具:StopWatch 计时器
    工具类:org.springframework.util.StopWatch作用:记录方法执行耗时,统计每个方法的耗时占比所在模块:spring-core方法描述voidstart(StringtaskName)开始一个新的监测任务,可设置任务名称。记录当前时间和任务名称voidstop()结束当前监测任务。记录任务执行......