Spring Boot 集成 Redis 核心依賴 spring-boot-starter-data-redis,配置簡單、開箱即用。

<!-- 添加依賴 -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>4.0.0</version>
</dependency>

在 application.yml 中配置 Redis 連接信息、連接池、序列化方式(核心)

spring:
  # Redis 核心配置
  redis:
    host: localhost # Redis 服務地址(遠程需填 IP)
    port: 6379      # 端口(默認 6379)
    password:       # Redis 密碼(無密碼留空,生產環境必須設置)
    database: 0     # 操作的數據庫索引(默認 0,Redis 支持 0-15 共 16 個庫)
    timeout: 3000ms # 連接超時時間(毫秒)
 
# Redis 自定義配置(可選,用於序列化)
redis:
  key-prefix: "app:" # Key 統一前綴(避免不同項目 Key 衝突)
  timeout: 3600      # 默認過期時間(秒,如 1 小時)

Spring Data Redis 默認的 RedisTemplate 使用 JdkSerializationRedisSerializer,會導致 Redis 中 Key/Value 帶亂碼(如 \xAC\xED\x00\x05t\x00\x03key),且不支持 JSON 存儲。必須自定義配置類,優化序列化方式:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Value("${redis.key-prefix:}")
    private String keyPrefix;  // 自定義 Key 前綴

    @Value("${redis.enable-prefix:true}")
    private boolean enablePrefix;  // 是否啓用 Key 前綴

    /**
     * 自定義 RedisTemplate:解決序列化亂碼 + 支持 JSON 存儲
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 1. Key 序列化:String 序列化(無亂碼,Redis 中可讀)
        StringRedisSerializer keySerializer = new StringRedisSerializer() {
            // 重寫序列化方法,自動添加前綴
            @Override
            public byte[] serialize(String key) {
                if (enablePrefix && key != null) {
                    key = keyPrefix + key;  // 拼接前綴
                }
                return super.serialize(key);
            }

            // 重寫反序列化方法,自動去除前綴(查詢時用)
            @Override
            public String deserialize(byte[] bytes) {
                String key = super.deserialize(bytes);
                if (enablePrefix && key != null && key.startsWith(keyPrefix)) {
                    return key.substring(keyPrefix.length());  // 截取前綴
                }
                return key;
            }
        };

        // 2. Value 序列化:JSON 序列化(支持對象存儲,保留類型信息)
        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();

        // 3. 綁定序列化器
        template.setKeySerializer(keySerializer);          // Key 序列化
        template.setValueSerializer(valueSerializer);        // Value 序列化
        template.setHashKeySerializer(keySerializer);       // Hash Key 序列化
        template.setHashValueSerializer(valueSerializer);   // Hash Value 序列化

        // 4. 初始化模板(必須調用,否則配置不生效)
        template.afterPropertiesSet();

        return template;
    }

    /**
     * 字符串專用模板(簡化 String 類型操作,官方已提供,可選重寫)
     */
    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        // 如需給 String  Key 加前綴,可重寫 KeySerializer(同上面的 keySerializer)
        return template;
    }
}