Spring Boot应用程序的休眠缓存(Infinispan,Hazelcast,理想情况下可扩展)

问题描述 投票:0回答:1

我有一个Spring Boot应用程序,它通过Hibernate检索(并存储)数据。 Hibernate已连接到MySQL数据库。在从数据库中检索某些表之前,我使用一些实体图对数据库请求进行了一些优化,以加入一些表。现在,我希望将最常见的对象(不会经常更改)存储在缓存中。

我尝试通过Infinispan和Hazelcast进行缓存。我在这里和那里更改了配置,但总是以某种方式从数据库中检索实体。

对于Halzelcast,我在pom.xml中添加了以下三个依赖项。即使hazelcast-hibernate似乎已集成在hazelcast-spring中,但我仍需要第三个依赖项,因为否则,区域工厂将不可用。

<dependency>
    <groupId>com.hazelcast</groupId>
    <artifactId>hazelcast</artifactId>
    <version>3.12.2</version>
</dependency>
<dependency>
    <groupId>com.hazelcast</groupId>
    <artifactId>hazelcast-spring</artifactId>
    <version>3.12.2</version>
</dependency>
<dependency>
    <groupId>com.hazelcast</groupId>
    <artifactId>hazelcast-hibernate53</artifactId>
    <version>1.3.2</version>
</dependency>

以下设置对于将Hazelcast用作Hibernate缓存应该足够了。但这行不通。我仍然像以前一样在日志中看到相同的SQL查询。

spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.region.factory_class=com.hazelcast.hibernate.HazelcastLocalCacheRegionFactory

HazelcastLocalCacheRegionFactory应该被使用,因为性能应该稍微好一些,而ram(当前)不是一个大问题。不过,我也欢迎采用其他方法。

[Infinispan也尝试过相同的方法(不同的依赖关系但相同的不存在的结果)。

我打算使用外部提供商,因为该应用程序应该可扩展。如果不注意这一点,缓存将无法再正确镜像数据库。

应该使用嵌入式缓存,因为用于Hazelcast或Infinispan的额外服务器太难维护了。

我不知道为什么什么都没有改变(好的,我看到Hazelcast开始了)。我的另一个想法是使用查询缓存而不是Hibernate缓存。但这需要更多注意以确保同步数据库和缓存。此外,该应用程序可能不会从中受益。

您能告诉我为什么它不起作用以及如何对其进行更改吗?

hibernate spring-boot caching hazelcast infinispan
1个回答
0
投票

我认为,无论缓存是否激活,SQL都将始终由Hibernate输出。如果您要确保使用缓存,请激活Hibernate统计信息:

spring.jpa.properties.hibernate.generate_statistics=true

在第一个请求上,它应该输出类似这样的内容:

Session Metrics {
    388816 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    2436908 nanoseconds spent preparing 1 JDBC statements;
    2585533 nanoseconds spent executing 1 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    10276363 nanoseconds spent performing 1 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    54012289 nanoseconds spent performing 1 L2C misses;
    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
    0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
}

并且在以后的请求中,类似:

Session Metrics {
    79940 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    0 nanoseconds spent preparing 0 JDBC statements;
    0 nanoseconds spent executing 0 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    1665675 nanoseconds spent performing 1 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
    0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
}

注意第二个请求的缓存命中。

© www.soinside.com 2019 - 2024. All rights reserved.