我使高速缓存具有永久性,并希望重新启动后直到有效之前不会重新填充它。但是每次重新启动后都会重新填充。
Ehcache配置:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.ehcache.org/v3"
xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
xsi:schemaLocation="
http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">
<persistence directory="spring-boot-ehcache/cache" />
<cache alias="pow_cache">
<key-type>org.springframework.cache.interceptor.SimpleKey</key-type>
<value-type>java.lang.Double</value-type>
<expiry>
<ttl unit="seconds">120</ttl>
</expiry>
<listeners>
<listener>
<class>my.pack.CacheEventLogger</class>
<event-firing-mode>ASYNCHRONOUS</event-firing-mode>
<event-ordering-mode>UNORDERED</event-ordering-mode>
<events-to-fire-on>CREATED</events-to-fire-on>
<events-to-fire-on>EXPIRED</events-to-fire-on>
</listener>
</listeners>
<resources>
<heap unit="entries">2</heap>
<offheap unit="MB">10</offheap>
<disk unit="MB" persistent="true">100</disk>
</resources>
</cache>
</config>
弹簧配置:
@Configuration
@EnableCaching
public class EhcacheConfig {
@Bean
public CacheManager cacheManager() throws URISyntaxException {
JCacheCacheManager jCacheCacheManager = new JCacheCacheManager(Caching.getCachingProvider().getCacheManager(
getClass().getResource("/ehcache.xml").toURI(),
getClass().getClassLoader()
));
javax.cache.CacheManager cacheManager = jCacheCacheManager.getCacheManager();
Cache<Object, Object> powCache = cacheManager.getCache("pow_cache");
return jCacheCacheManager;
}
}
服务:
@Cacheable(value = "pow_cache", unless = "#pow==3||#result>100", condition = "#val<5")
public Double pow(int val, int pow) throws InterruptedException {
System.out.println(String.format("REAL invocation myService.pow(%s, %s)", val, pow));
Thread.sleep(3000);
return Math.pow(val, pow);
}
和主要
:ConfigurableApplicationContext context = SpringApplication.run(Main.class);
MyService myService = context.getBean(MyService.class);
System.out.println(String.format("invoke myService.pow(%s, %s)", 4, 2));
System.out.println("result = " + myService.pow(4, 2));
输出:
invoke myService.pow(4, 2)
REAL invocation myService.pow(4, 2)
2019-09-12 23:44:56.819 INFO 7300 --- [e [_default_]-0] my.pack.CacheEventLogger : Cache event CREATED for item with key SimpleKey [4,2]. Old value = null, New value = 16.0
result = 16.0
立即重启后,我看到相同的输出(缓存重新填充)。重新启动后,如果仍然有效,如何实现不重新填充缓存?
我注意到有时在最后一行打印和应用程序关闭之间会有一些延迟。如果等待应用程序关闭-重新启动后不要重新填充缓存。