如何在Hibernate中使用Redis作为L2缓存?

huangapple go评论64阅读模式
英文:

How to use Redis as L2 cache on Hibernate?

问题

我有一个Spring Boot应用程序,需要将Redis设置为Hibernate的二级缓存。

我的属性文件如下:

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,我发现所有使用@Cacheable注解的实体在使用命令keys *时都会被列出。到这里,我认为一切都运行正常,但是通过使用Postgres记录资源,我发现查询仍然在命中数据库。

是否有人有任何提示可以使其正常工作?

英文:

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?

答案1

得分: 0

你应该使用 .setCachable(true) 来使查询在 Hibernate 层级上被缓存。
查看这个文档。

此外,参考这个关于 Hibernate 二级缓存的问题。

英文:

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

答案2

得分: 0

我发现使用Hibernate的@Cacheable可以解决所有问题。

英文:

I found out that using @Cacheable from hibernate will solve everything.

huangapple
  • 本文由 发表于 2020年9月19日 04:55:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63962733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定