使用Redis作为Spring缓存管理器来缓存自定义的Java对象。

4
我想将Redis用作缓存管理器,以便缓存来自MySQL数据库的JPA实体
我对Redis不熟悉,似乎Redis只能缓存它所知道的基本类型/结构(如字符串、哈希等)
我的问题是:我可以使用Redis(与Spring缓存抽象一起)作为Spring缓存管理器来缓存我的自定义对象(例如Person, Order, Customer等)吗?
2个回答

4
您可以先查看Spring Data Redis,但不同于Spring Data JPA,它没有提供存储库抽象层,而是使用仅适用于Redis的Spring模板和访问器方法。由于Redis不支持关系,您需要通过覆盖JPA标准CRUD操作来设计和实现这些关系。
下面是一篇很棒的文章,详细介绍了与您相关的内容...
http://www.packtpub.com/article/building-applications-spring-data-redis

我对Redis很陌生,似乎只能缓存它所知道的基本类型/结构(例如字符串、哈希等)

Redis可以存储任何东西;文本、JSON、二进制数据等都可以。
默认情况下,RedisTemplate(Spring Data Redis的一部分)使用Java序列化将对象编组/解组到Redis中,但与MessagePack等相比,它在Redis中占用更多的空间,据我的测试结果。

谢谢您的回复。最后一个问题:我能否直接使用Redis Spring Cache管理器与Spring缓存抽象,还是需要进一步配置? - balteo
我不太确定,但我建议先看一下这篇文章作为教程,跟着构建它,这样会有很多问题得到解答。 - raffian
1
Spring Data Redis 中有 RedisCacheManager 实现。JavaDocs - Ricardo Pardini

3
Redisson提供了基于Redis的Spring缓存提供程序。它支持Redis存储的重要缓存设置,如ttlmaxIdleTime,并支持许多流行的编解码器:Jackson JSONAvroSmileCBORMsgPackKryoFSTLZ4SnappyJDK 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);
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接