【问题标题】:Using Redis as the Spring cache manager in order to cache custom java objects使用 Redis 作为 Spring 缓存管理器以缓存自定义 java 对象
【发布时间】:2013-08-06 00:15:46
【问题描述】:

我想使用 Redis 作为 缓存管理器,以便缓存来自 MySQL 数据库的 JPA 实体

我是 Redis 新手,似乎 Redis 只能缓存它知道的基本类型/结构(字符串、哈希等)

我的问题是:我可以使用 Redis(连同 Spring 缓存抽象)作为 Spring 缓存管理器来缓存我的自定义对象(比如 PersonOrderCustomer、等等...)?

【问题讨论】:

    标签: spring caching redis


    【解决方案1】:

    您可以从查看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 中使用更多空间。

    【讨论】:

    • 感谢您的回复。最后一个问题:我可以按原样使用带有 Spring 缓存抽象的 Redis Spring Cache 管理器,还是需要进一步配置?
    • 我不完全确定,我会从那篇文章作为教程开始,构建它,它肯定会回答很多问题。
    • Spring Data Redis 中有一个 RedisCacheManager 实现。 JavaDocs
    【解决方案2】:

    Redisson 提供基于 Redis 的 Spring Cache 提供程序。它支持 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);
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-22
      • 2018-11-29
      • 1970-01-01
      • 2016-03-29
      • 2016-04-02
      • 2013-09-02
      • 2015-12-08
      • 2020-03-13
      • 2017-06-16
      相关资源
      最近更新 更多