Spring Boot集成Redis Search快速入门Demo

1.什么是Redis Search?

RedisSearch 是一个基于 Redis 的搜索引擎模块,它提供了全文搜索、索引和聚合功能。通过 RedisSearch,可以为 Redis 中的数据创建索引,执行复杂的搜索查询,并实现高级功能,如自动完成、分面搜索和排序。利用 Redis 的高性能特点,RedisSearch 可以实现高效的搜索和实时分析。对于微服务架构来说,RedisSearch 可以作为搜索服务的一部分,提供快速、高效的搜索能力,对于提高用户体验和性能具有重要的意义。

2.环境搭建

Docker Compose

yaml 复制代码
version: '3'
services:

  redis:
    image: redis/redis-stack
    container_name: redis
    ports:
      - 6379:6379

  redis-insight:
    image: redislabs/redisinsight
    container_name: redis-insight
    ports:
      - 8001:8001

Run following command:

docker-compose up -d

3.代码工程

实验目的

利用redis search 实现文本搜索功能

pom.xml

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.1</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>RedisSearch</artifactId>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>
    <dependencies>


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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.redis.om</groupId>
            <artifactId>redis-om-spring</artifactId>
            <version>0.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>


    </dependencies>
</project>

controller

kotlin 复制代码
package com.et.controller;


import com.et.redis.document.Student;
import com.et.redis.document.StudentRepository;
import com.et.redis.hash.Person;
import com.et.redis.hash.PersonRepository;
import jakarta.websocket.server.PathParam;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


@RestController
public class WebController {

    private PersonRepository personRepository;
    private StudentRepository studentRepository;

    public WebController(PersonRepository personRepository, StudentRepository studentRepository) {
        this.personRepository = personRepository;
        this.studentRepository = studentRepository;
    }

    @PostMapping("/person")
    public Person save(@RequestBody Person person) {
        return personRepository.save(person);
    }

    @GetMapping("/person")
    public Person get(@PathParam("name") String name, @PathParam("searchLastName") String searchLastName) {
        if (name != null)
            return this.personRepository.findByName(name)
                    .orElseThrow(() -> new RuntimeException("person not found"));

        if (searchLastName != null)
            return this.personRepository.searchByLastName(searchLastName)
                    .orElseThrow(() -> new RuntimeException("person not found"));

        return null;
    }

// ---- Student Endpoints
    @PostMapping("/student")
    public Student saveStudent(@RequestBody Student student) {
        return studentRepository.save(student);
    }

    @GetMapping("/student")
    public Student getStudent(@PathParam("name") String name, @PathParam("searchLastName") String searchLastName) {
        if (name != null)
            return this.studentRepository.findByName(name)
                    .orElseThrow(() -> new RuntimeException("Student not found"));

        if (searchLastName != null)
            return this.studentRepository.searchByLastName(searchLastName)
                    .orElseThrow(() -> new RuntimeException("Student not found"));

        return null;
    }
    @ExceptionHandler(value = RuntimeException.class)
    public ResponseEntity handleError(RuntimeException e) {
        return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(e.getMessage());
    }


}

@RedisHash 方式

typescript 复制代码
package com.et.redis.hash;

import com.redis.om.spring.annotations.Indexed;
import com.redis.om.spring.annotations.Searchable;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;

@RedisHash
public class Person {

    @Id
    private String id;
    @Indexed
    private String name;

    @Searchable
    private String lastName;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

package com.et.redis.hash;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface PersonRepository extends CrudRepository<Person, String> {

    Optional<Person> findByName(String name);
    Optional<Person> searchByLastName(String name);
}

@Document 方式

typescript 复制代码
package com.et.redis.document;

import com.redis.om.spring.annotations.Document;
import com.redis.om.spring.annotations.Indexed;
import com.redis.om.spring.annotations.Searchable;
import org.springframework.data.annotation.Id;

@Document
public class Student {

    @Id
    private String id;
    @Indexed
    private String name;

    @Searchable
    private String lastName;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

package com.et.redis.document;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface StudentRepository extends CrudRepository<Student, String> {

    Optional<Student> findByName(String name);
    Optional<Student> searchByLastName(String name);
}

DemoApplication

kotlin 复制代码
package com.et;

import com.redis.om.spring.annotations.EnableRedisDocumentRepositories;
import com.redis.om.spring.annotations.EnableRedisEnhancedRepositories;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@EnableRedisDocumentRepositories(basePackages = "com.et.redis.document")
@EnableRedisEnhancedRepositories(basePackages = "com.et.redis.hash")
@SpringBootApplication
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

application.yaml

yaml 复制代码
server:
  port: 8088
spring:
  redis:
    host: localhost
    port: 6379

只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

4.测试

启动Spring boot应用

测试hash方式

插入一个实体

查询

模糊查询redis数据(*rab*)

查看redis数据库数据

redis数据库模糊查询

测试json document方式

同样的方式插入json文档,然后在你redis数据库里面查看

5.引用

相关推荐
DevOpsDojo6 分钟前
HTML语言的数据结构
开发语言·后端·golang
东软吴彦祖25 分钟前
包安装利用 LNMP 实现 phpMyAdmin 的负载均衡并利用Redis实现会话保持nginx
linux·redis·mysql·nginx·缓存·负载均衡
一只淡水鱼6633 分钟前
【spring原理】Bean的作用域与生命周期
java·spring boot·spring原理
时韵瑶43 分钟前
Scala语言的云计算
开发语言·后端·golang
Jerry Lau1 小时前
大模型-本地化部署调用--基于ollama+openWebUI+springBoot
java·spring boot·后端·llama
小白的一叶扁舟1 小时前
Kafka 入门与应用实战:吞吐量优化与与 RabbitMQ、RocketMQ 的对比
java·spring boot·kafka·rabbitmq·rocketmq
幼儿园老大*1 小时前
【系统架构】如何设计一个秒杀系统?
java·经验分享·后端·微服务·系统架构
fmdpenny1 小时前
Django的安装
后端·python·django
计算机-秋大田1 小时前
基于SSM的家庭记账本小程序设计与实现(LW+源码+讲解)
java·前端·后端·微信小程序·小程序·课程设计
Code侠客行1 小时前
Scala语言的循环实现
开发语言·后端·golang