是否可以自定义 Spring 缓存抽象使用的序列化?

Is it possible to customize serialization used by the Spring Cache abstraction?

我有一个使用 Redis 进行缓存的 Java 网络服务。最初我创建了一个直接访问 Redisson 客户端的 CacheService 以处理缓存。我最近重构了缓存处理以使用 Spring 缓存抽象,这使代码更清晰并鼓励模块化设计。不幸的是,Spring 使用 Jackson 来 serialize/deserialize 缓存对象,由于类型信息存储在 JSON 中,导致缓存值比以前大得多。这导致从缓存读取的响应时间增加到不可接受的程度。有什么方法可以自定义Spring序列化和反序列化缓存内容的方式吗?我想用我自己的逻辑替换它,但在文档中看不到任何内容。如果可能的话,我宁愿不必推出自己的 AspectJ 缓存实现。

RedisCacheManager 需要一个 RedisOperations,您可以在那里配置序列化的工作方式。您可以调整键和值的序列化,但我怀疑键应该使用 StringRedisSerializer.

Redisson also provides Spring Cache integration。它支持许多流行的编解码器:Jackson JSON、Avro、Smile、CBOR、MsgPack、Kryo、FST、LZ4、Snappy 和 JDK Serialization。

这是一个例子:

@Bean
CacheManager cacheManager(RedissonClient redissonClient) {
    Codec codec = new JsonJacksonCodec();

    Map<String, CacheConfig> config = new HashMap<String, CacheConfig>();
    config.put("testMap", new CacheConfig(24*60*1000, 12*60*1000));
    return new RedissonSpringCacheManager(redissonClient, config, codec);
}