简体   繁体   中英

How to use Redis as L2 cache on Hibernate?

I have a spring boot application and need to setup Redis as l2 cache on hibernate.

My prop file looks like:

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

I created a custom region factory because I don't want to use json or yaml files. (right now, the parameters are hardcoded). CustomRegionFactory class looks like:

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);
    }
}

Using redis-cli I found out that all my entities annotated with @Cacheable are listed when using the command keys * . Until here I thought everything worked fine, but using the postgres logging resources I found out that the queries are hitting the database.

Does somebody have any tips to make it works?

You should use .setCachable(true) to make queries to be cached on hibernate level. See this documentaion.

Also see this question regarding second level cache on hibernate

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM