> ## Documentation Index
> Fetch the complete documentation index at: https://blog.pig4cloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Redis 8.0 与 Spring Boot 完美融合：JSON、AI 搜索等新特性实战指南

> 深入探索 Redis 8.0 的革命性特性，包括原生 JSON 支持、向量搜索、新的原子操作命令等，以及如何在 Spring Boot 应用中充分利用这些功能。

Redis 8.0 版本于 2025 年 5 月发布，不仅仅是一个增量更新，而是一个变革性的版本，从根本上扩展了 Redis 的开箱即用功能。

多年来，开发者通过强大的模块如 RediSearch、RedisJSON 和 RedisTimeSeries 来扩展 Redis 的核心功能。Redis 8.0 通过将这些功能直接集成到主二进制文件中来简化这种体验。结果是一个统一且功能强大的工具，为现代数据密集型应用程序做好了准备，从实时分析到生成式 AI。

让我们深入了解 Redis 8.0 中最令人兴奋的新特性，看看它们如何彻底改变您的工作流程。

## 环境准备 🛠️

在深入之前，让我们先设置 Spring Boot 项目。您需要在 `pom.xml` 中添加以下依赖项。我们将包含标准的 Redis starter 和 Spring AI starter 用于向量搜索示例。

```xml theme={null}
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

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

    <dependency>
      <groupId>org.springframework.ai</groupId>
      <artifactId>spring-ai-advisors-vector-store</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-starter-vector-store-redis</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.ai</groupId>
      <artifactId>spring-ai-starter-model-openai</artifactId>
    </dependency>
        
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>
```

在 `application.properties` 中配置 Redis 和 OpenAI 凭据：

```properties theme={null}
# Redis 配置
spring.data.redis.host=localhost
spring.data.redis.port=6379

# Spring AI 配置
spring.ai.openai.api-key=API_KEY
```

## 1. 原生 JSON 文档支持 📄

Redis 8.0 最重要的变化之一是将 RedisJSON 模块集成到核心中。现在您可以存储、检索和对复杂的 JSON 文档执行原子部分更新，而无需获取整个对象。

### Redis 命令示例：管理汽车信息

让我们存储一辆汽车的信息，然后更新单个字段：

```bash theme={null}
# 为汽车 ID 'car:001' 设置 JSON 文档
> JSON.SET car:001 $ '{"id": "car001", "brand": "Tesla", "model": "Model S", "year": 2023, "price": 89999.99, "color": "白色", "fuelType": "电动", "mileage": 15000, "features": ["自动驾驶", "全景天窗"]}'
OK

# 向汽车功能列表添加新功能
> JSON.ARRAPPEND car:001 $.features '"无线充电"'
"[3]"

# 更新汽车里程数
> JSON.NUMINCRBY car:001 $.mileage 1000
"[16000]"

# 仅检索汽车的品牌和型号
> JSON.GET car:001 $.brand $.model
"[\"Tesla\", \"Model S\"]"

# 检索汽车的所有功能
> JSON.GET car:001 $.features
"[\"自动驾驶\", \"全景天窗\", \"无线充电\"]"
```

### Spring Boot 示例：缓存汽车信息

让我们想象有一个 Car 类，我们希望将其作为 JSON 对象缓存在 Redis 中。

**Car POJO（使用 Lombok 简化）：**

```java theme={null}
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Car {
    private String id;
    private String brand;
    private String model;
    private int year;
    private double price;
    private String color;
    private String fuelType;
    private int mileage;
    private List<String> features;
}
```

**Car Service：**

我们可以使用配置为处理 JSON 字符串的标准 RedisTemplate，并利用 Jackson 的 ObjectMapper 进行序列化。

```java theme={null}
@Service
public class CarService {
    private static final String CAR_KEY_PREFIX = "car:";
    private final RedisTemplate<String, String> redisTemplate;
    private final ObjectMapper objectMapper;
    
    public CarService(RedisTemplate<String, String> redisTemplate, ObjectMapper objectMapper) {
        this.redisTemplate = redisTemplate;
        this.objectMapper = objectMapper;
    }
    
    public void saveCar(Car car) throws JsonProcessingException {
        String carJson = objectMapper.writeValueAsString(car);
        redisTemplate.opsForValue().set(CAR_KEY_PREFIX + car.getId(), carJson);
    }
    
    public Car getCar(String id) throws JsonProcessingException {
        String carJson = redisTemplate.opsForValue().get(CAR_KEY_PREFIX + id);
        if (carJson != null) {
            return objectMapper.readValue(carJson, Car.class);
        }
        return null; // 或从主数据库获取
    }
    
    public void updateCarMileage(String carId, int newMileage) throws JsonProcessingException {
        Car car = getCar(carId);
        if (car != null) {
            car.setMileage(newMileage);
            saveCar(car);
        }
    }
    
    public List<Car> searchCarsByBrand(String brand) {
        // 这里可以结合 Redis 查询引擎进行更复杂的搜索
        // 为了演示，这里返回模拟数据，使用 Lombok 的 Builder 模式
        return Arrays.asList(
            Car.builder()
                .id("car1")
                .brand(brand)
                .model("Model S")
                .year(2023)
                .price(89999.99)
                .color("白色")
                .fuelType("电动")
                .mileage(15000)
                .features(Arrays.asList("自动驾驶", "全景天窗", "真皮座椅"))
                .build()
        );
    }
}
```

这种方法简洁高效，让您能够直接在 Spring 中利用 Redis 作为丰富的文档缓存。

## 2. AI 革命：使用 Spring AI 进行向量相似性搜索 🧠

也许最具前瞻性的特性是新的向量集数据结构（目前处于测试阶段），巩固了 Redis 在 AI 生态系统中的地位。向量搜索允许您基于语义含义而不是精确关键词来查找数据，这是现代 AI 功能的支柱，如 RAG（检索增强生成）、推荐引擎和图像搜索。

### Redis 命令示例：存储和查询图像向量

想象您有图像的向量嵌入。您可以存储它们并找到最相似的图像。

```bash theme={null}
# 为具有 128 维的图像向量创建向量集
> VSET.CREATE image_vectors 128

# 为两个图像添加向量
> VSET.ADD image_vectors image:a '[0.12, 0.45, ..., 0.81]'
> VSET.ADD image_vectors image:b '[0.13, 0.44, ..., 0.80]'

# 找到与给定查询向量最相似的 3 个图像
> VSET.SIMILARITY_SEARCH image_vectors '[0.11, 0.46, ..., 0.79]' K 3
1) "image:b"
2) "image:a"
3) ...
```

### Spring Boot 示例：构建语义搜索服务

让我们构建一个服务，您可以存储文本文档并找到相似的文档。

**VectorStore 配置：**

首先，我们需要配置 VectorStore bean，Spring AI 将使用它与 Redis 交互。

```java theme={null}
@Configuration
public class AiConfiguration {
    @Bean
    public VectorStore vectorStore(EmbeddingClient embeddingClient) {
        RedisVectorStore.RedisVectorStoreConfig config = RedisVectorStore.RedisVectorStoreConfig.builder()
            .withIndexName("my-app-vectors")
            .withPrefix("vector:")
            .build();
        return new RedisVectorStore(config, embeddingClient);
    }
}
```

**语义搜索服务：**

此服务将接受文本，使用 AI 模型（如 OpenAI 的）对其进行嵌入，将其存储在 Redis 中，并允许您搜索相似内容。

```java theme={null}
@Service
public class SemanticSearchService {
    private final VectorStore vectorStore;
    
    public SemanticSearchService(VectorStore vectorStore) {
        this.vectorStore = vectorStore;
    }
    
    public void addDocument(String content) {
        vectorStore.add(List.of(new Document(content)));
        System.out.println("文档已添加到 Redis 向量存储。");
    }
    
    public List<Document> findSimilarDocuments(String query, int topK) {
        System.out.println("为查询 '" + query + "' 查找 " + topK + " 个相似文档");
        return vectorStore.similaritySearch(query, topK);
    }
}
```

仅用几行代码，您就已经将强大的语义搜索引擎集成到您的 Spring Boot 应用程序中，全部由 Redis 8.0 提供支持。

## 3. 开发者体验提升：新的原子哈希命令

`HGETDEL` 命令是一个完美的例子。它允许您从哈希中检索字段的值并在单个原子操作中删除该字段。这对于处理存储在 Redis 哈希中的队列任务非常理想。

### Spring Boot 示例：简单任务处理器

```java theme={null}
@Service
public class TaskProcessorService {
    private final StringRedisTemplate redisTemplate;
    private static final String TASK_QUEUE_KEY = "task_queue";
    
    public TaskProcessorService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    
    public void addTask(String taskId, String taskData) {
        redisTemplate.opsForHash().put(TASK_QUEUE_KEY, taskId, taskData);
    }
    
    public String claimTask(String taskId) {
        // 使用 HGETDEL 原子地获取和删除任务
        byte[] taskDataBytes = redisTemplate.execute(new RedisCallback<byte[]>() {
            @Override
            public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.hashCommands().hGetDel(
                    TASK_QUEUE_KEY.getBytes(), 
                    taskId.getBytes()
                );
            }
        });
        return (taskDataBytes != null) ? new String(taskDataBytes) : null;
    }
}
```

这种模式确保一旦工作者声明了任务，其他工作者就不能意外地处理同一个任务——全部通过单个高效的命令完成。

## 4. Redis 查询引擎：超越键值查找

虽然 Redis 在基于键的查找方面表现出色，但现实世界的应用程序通常需要根据数据内容来查询数据。新的 Redis 查询引擎现在是核心功能，允许您在 Hash 和 JSON 数据上创建二级索引。

这意味着您可以执行复杂的多字段查询，而无需维护手动索引，使您的应用程序逻辑更简单、更强大。

### 代码示例：索引和搜索汽车

假设您将汽车信息存储在哈希中。您可以创建索引以按品牌、价格、年份等条件查找汽车。

```bash theme={null}
# 为以 'car:' 开头的哈希中存储的汽车创建索引
> FT.CREATE car_idx ON HASH PREFIX 1 "car:" SCHEMA brand TAG SORTABLE price NUMERIC SORTABLE year NUMERIC SORTABLE fuelType TAG color TAG
OK

# 添加一些汽车
> HSET car:1 brand "Tesla" model "Model S" price 89999.99 year 2023 color "白色" fuelType "电动" mileage 15000

# 搜索品牌为 "Tesla" 且价格低于 $60000 的所有汽车
> FT.SEARCH car_idx "@brand:{Tesla} @price:[0 60000]"
1) (integer) 1
2) "car:3"
3) 1) "brand"
   2) "Tesla"
   3) "model"
   4) "Model 3"
   5) "price"
   6) "45999.99"
   7) "year"
   8) "2022"
   9) "color"
   10) "红色"
   11) "fuelType"
   12) "电动"
```

## 5. 底层优化：新的 I/O 线程模型

对于高级用户，Redis 8.0 引入了改进的 I/O 线程实现。通过设置 `io-threads` 配置参数（例如，`io-threads 8`），您可以利用现代多核 CPU 实现吞吐量的大幅增加——在基准测试中每秒操作数增加高达 2 倍。这允许单个 Redis 实例处理更多要求苛刻的工作负载。

## 总结

Redis 8.0 不仅仅是一个数据库升级，它是现代应用程序架构的一个重要里程碑。结合 Spring Boot 的强大功能，开发者现在可以构建更智能、更快速、更具扩展性的应用程序。
