【发布时间】:2013-08-06 00:15:46
【问题描述】:
我想使用 Redis 作为 缓存管理器,以便缓存来自 MySQL 数据库的 JPA 实体。
我是 Redis 新手,似乎 Redis 只能缓存它知道的基本类型/结构(字符串、哈希等)
我的问题是:我可以使用 Redis(连同 Spring 缓存抽象)作为 Spring 缓存管理器来缓存我的自定义对象(比如 Person、Order、Customer、等等...)?
【问题讨论】:
我想使用 Redis 作为 缓存管理器,以便缓存来自 MySQL 数据库的 JPA 实体。
我是 Redis 新手,似乎 Redis 只能缓存它知道的基本类型/结构(字符串、哈希等)
我的问题是:我可以使用 Redis(连同 Spring 缓存抽象)作为 Spring 缓存管理器来缓存我的自定义对象(比如 Person、Order、Customer、等等...)?
【问题讨论】:
您可以从查看Spring Data Redis 开始,但与 Spring Data JPA 不同的是,它不提供存储库抽象,而是使用带有仅针对 redis 的访问器方法的 Spring 模板。由于 Redis 不支持关系,因此您必须通过覆盖 JPA 的标准 CRUD 操作来设计和实现这些关系。
这是一篇很棒的文章,详细介绍了你的小巷...
http://www.packtpub.com/article/building-applications-spring-data-redis
我是 Redis 新手,似乎 Redis 只能缓存基本的 它知道的类型/结构(字符串、哈希等)
Redis 可以存储任何东西; text、json、二进制数据,没关系。
默认情况下,RedisTemplate(Spring Data Redis 的一部分)使用 Java 序列化将对象编组/解组到 redis,但根据我的测试,与 MessagePack 之类的东西相比,它在 redis 中使用更多空间。
【讨论】:
Redisson 提供基于 Redis 的 Spring Cache 提供程序。它支持 Redis 存储的 ttl 和 maxIdleTime 等重要缓存设置,并支持许多流行的编解码器:Jackson JSON、Avro、Smile、CBOR、MsgPack、Kryo、FST 、LZ4、Snappy 和 JDK Serialization。
配置示例如下:
@Configuration
@ComponentScan
@EnableCaching
public static class Application {
@Bean(destroyMethod="shutdown")
RedissonClient redisson() {
Config config = ...
return Redisson.create(config);
}
@Bean
CacheManager cacheManager(RedissonClient redissonClient) throws IOException {
Map<String, CacheConfig> config = new HashMap<String, CacheConfig>();
// ttl = 24 mins, maxIdleTime = 12 mins
config.put("testCache", new CacheConfig(24*60*1000, 12*60*1000));
return new RedissonSpringCacheManager(redissonClient, config);
}
}
【讨论】: