【问题标题】:Is it possible to customize serialization used by the Spring Cache abstraction?是否可以自定义 Spring Cache 抽象使用的序列化?
【发布时间】:2016-10-11 18:10:36
【问题描述】:
我有一个使用 Redis 进行缓存的 Java Web 服务。最初,我创建了一个直接访问 Redisson 客户端以处理缓存的 CacheService。我最近重构了缓存处理以使用 Spring Cache 抽象,这使代码更加简洁并鼓励模块化设计。不幸的是,Spring 使用 Jackson 来序列化/反序列化缓存对象,导致缓存值比以前大得多,因为类型信息存储在 JSON 中。这导致从缓存中读取的响应时间增加了令人无法接受的程度。有没有办法自定义 Spring 对缓存内容进行序列化和反序列化的方式?我想用我自己的逻辑替换它,但在文档中看不到任何内容。如果可能的话,我宁愿不必推出自己的 AspectJ 缓存实现。
【问题讨论】:
标签:
java
spring
redis
jackson
spring-cache
【解决方案1】:
RedisCacheManager 采用RedisOperations,您可以在那里配置序列化的工作方式。尽管我怀疑键应该使用StringRedisSerializer,但您可以调整键和值的序列化。
【解决方案2】:
Redisson 还提供Spring Cache integration。它支持许多流行的编解码器:Jackson JSON、Avro、Smile、CBOR、MsgPack、Kryo、FST、LZ4、Snappy 和 JDK 序列化。
这是一个例子:
@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);
}