【问题标题】:How to use Redis as L2 cache on Hibernate?如何在 Hibernate 上使用 Redis 作为 L2 缓存?
【发布时间】:2020-09-18 20:55:37
【问题描述】:

我有一个 Spring Boot 应用程序,需要在休眠时将 Redis 设置为 l2 缓存。

我的道具文件看起来像:

spring.jpa.properties.hibernate.cache.region.factory_class = package.CustomRegionFactory
spring.jpa.properties.hibernate.cache.redisson.fallback=false

我创建了一个自定义区域工厂,因为我不想使用 json 或 yaml 文件。 (现在,参数是硬编码的)。 CustomRegionFactory 类看起来像:

public class CustomRegionFactory extends RedissonRegionFactory {

    @Override
    public RedissonClient createRedissonClient(Properties properties) {     
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379").setRetryInterval(1500)
                .setRetryAttempts(3).setConnectTimeout(10000)
                .setClientName("client1");

        return Redisson.create(config);
    }
}

使用 redis-cli 我发现在使用命令 keys * 时,我所有用 @Cacheable 注释的实体都被列出了。直到这里,我认为一切正常,但使用 postgres 日志记录资源,我发现查询正在访问数据库。

有人有什么技巧可以让它发挥作用吗?

【问题讨论】:

    标签: java hibernate caching redis


    【解决方案1】:

    您应该使用 .setCachable(true) 将查询缓存在休眠级别。 请参阅this 文档。

    另见this关于休眠二级缓存的问题

    【讨论】:

      【解决方案2】:

      我发现在 hibernate 中使用 @Cacheable 可以解决所有问题。

      【讨论】:

        猜你喜欢
        • 2021-10-03
        • 1970-01-01
        • 2016-11-03
        • 2017-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-26
        • 2013-02-10
        相关资源
        最近更新 更多