Spring Boot Data Redis 自定义配置

完整配置如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
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.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * Redis 配置类
 *
 * @author Tofuwine
 */
@Configuration
@EnableCaching
@RequiredArgsConstructor
public class RedisConfig {

    private final Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder;

    /**
     * Redis 模板 Bean 配置
     *
     * @param redisConnectionFactory Redis 连接工厂
     * @return Redis 模板
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(StandardCharsets.UTF_8);
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);

        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(objectMapper());
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    /**
     * Redis 缓存管理器 Bean 配置
     *
     * @param redisConnectionFactory Redis 连接工厂
     * @return Redis 缓存管理器
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofDays(7))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer(StandardCharsets.UTF_8)))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer(objectMapper())))
                .disableCachingNullValues();

        // 自定义缓存过期时间 (单独配置)

        Map<String, RedisCacheConfiguration> cacheConfigs = new HashMap<>();
//        cacheConfigs.put("", defaultCacheConfig.entryTtl(Duration.ofDays(1)));

        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(defaultCacheConfig)
                .withInitialCacheConfigurations(cacheConfigs)
                .build();
    }

    /**
     * 自定义 ObjectMapper Bean 配置 (仅供 Redis 缓存使用)
     *
     * @return ObjectMapper
     */
    private ObjectMapper objectMapper() {
        ObjectMapper cacheObjectMapper = jackson2ObjectMapperBuilder.build();
        cacheObjectMapper.activateDefaultTyping(
                LaissezFaireSubTypeValidator.instance, // 类型验证器
                ObjectMapper.DefaultTyping.NON_FINAL,  // 为非 final 类添加类型信息
                JsonTypeInfo.As.PROPERTY               // 类型信息作为 JSON 属性(@class 字段)
        );
        return cacheObjectMapper;
    }
}

代码说明:

  • 保持了默认的 Spring Boot Data Redis 模板配置。
  • 使用自定义 ObjectMapper 配置 Redis 缓存,解决缓存中存储的对象类型信息丢失问题。
  • 配置了默认缓存过期时间为 7 天,可根据实际需求调整。
  • 提供了自定义缓存过期时间的配置方法,可根据需要为不同缓存设置不同的过期时间。

如果本文对您有所帮助,欢迎打赏支持作者!

Licensed under CC BY-NC-SA 4.0
最后更新于 2025-12-12 13:20
使用 Hugo 构建
主题 StackJimmy 设计