我需要为国家、地区等少数 bean实现只读缓存。
为了检查它们是否真的被缓存了,我使用 spring编写了一个集成测试。测试不太合适,它只是对我想要得到的东西的验证。您可以将其用作提示并实现自己的提示。
您可以在此处阅读有关如何使用 spring 编写集成测试的文章。
@Configurable(autowire = Autowire.BY_NAME)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class HibernateCachingTestIntg {
@Autowired
private ConfigurationDAO configurationDAO;
@Autowired
private CountryDAO countryDAO;
@Test
public void testGetCountries() {
for (int i = 0; i < 5; i++) {
StopWatch sw = new StopWatch("C");
sw.start();
countryDAO.listCountries();
sw.stop();
System.out.println(sw);
}
}
@Test
public void testGetRegionList() {
for (int i = 0; i < 5; i++) {
StopWatch sw = new StopWatch("R");
sw.start();
configurationDAO.getRegionList();
sw.stop();
System.out.println(sw);
}
}
}
这是输出: -
StopWatch 'C': running time (millis) = 217; [] took 217 = 100%
StopWatch 'C': running time (millis) = 15; [] took 15 = 100%
StopWatch 'C': running time (millis) = 16; [] took 16 = 100%
StopWatch 'C': running time (millis) = 15; [] took 15 = 100%
StopWatch 'C': running time (millis) = 16; [] took 16 = 100%
StopWatch 'R': running time (millis) = 201; [] took 201 = 100%
StopWatch 'R': running time (millis) = 15; [] took 15 = 100%
StopWatch 'R': running time (millis) = 0; [] took 0 = 0%
StopWatch 'R': running time (millis) = 16; [] took 16 = 100%
StopWatch 'R': running time (millis) = 15; [] took 15 = 100%
正如您在此处看到的,查询第一次执行需要更多时间,而后执行时间更少。如果您打开查询记录器,您可以看到SQL只是第一次被触发。