我正在尝试使用最小设置创建具有L2缓存的存储库。我的数据库是PostgreSQL。
我从使用maven的spring-boot-sample-data-jpa-archetype项目开始。我已经删除了HSQL并创建了一个DataSource bean来连接到postgresql。还使用ddl创建schema并导入初始脚本数据。
我还将@Cacheable添加到我的实体中。然后我使用单元测试使用仓库查询一个实体10次。时间为1~ 49 ms。所以我有两个问题。
1.存储库是否受益于L1缓存?我怎么知道我是在访问该高速缓存还是数据源?
1.如何启用二级缓存?Spring Data 有自己的实现吗?
2条答案
按热度按时间mefy6pfw1#
经过一些测试和@dunni的帮助,我会回答我自己的问题。Spring使用Hibernate作为JPA的实现。Spring data提供了一些对Hibernate的 Package 。还需要选择缓存实现。
若要启用二级缓存,请将这些属性添加到项目中。
还添加以下依赖项: hibernate
然后,将@Cacheable(true)添加到实体模型类。扩展一个repository接口,Spring将使用命名约定生成实现。比如说,
也可以实现接口。但这需要向查询对象添加一个提示来激活二级缓存。
要验证该高速缓存是否正常工作,可以使用以下属性查看SQL是否已执行。
uinbv5nw2#
在阅读了你的评论并检查了我的代码后,我的代码开始工作了。另外,通过添加
spring.jpa.properties.hibernate.generate_statistics=true
,我可以更详细地查看我的数据库调用。demo project link谢谢你