我想使用Ehcache和java配置(而不是通过xml)在spring jpa存储库中实现缓存功能。但是我对@cache,@caceevict,@cacheable,@caching注解感到困惑。
1)我想从缓存中有数据,如果数据在缓存中不可用,那么它应该从数据库中提取。
2)在控制器中,如果我点击/api/cacheRefresh,它应该刷新所有的表。
发布于 2017-11-06 19:01:41
在一个典型的应用程序中,你会有这样的层:
可以访问您的“存储”(例如db、nosql等)的
所需的所有数据。
您通常不会将缓存放在存储库层上,而是应该在服务层上完成。因此,为了回答您的问题,您应该让JPA存储库尽可能干净,并在访问存储库的服务上放置@Cacheable/@CacheEvict注释,例如:
public class MyService {
private final MyRepository repository;
public MyService(MyRepository repository) {
this.repository = repository;
}
@Cacheable
public MyItem findOne(Long id) {
return repository.findOne(id);
}
@Cacheable
public List<MyItem> findAll() {
return repository.findAll();
}
@CacheEvict
public void evict() {
}
}最终,当您需要刷新缓存时,可以从控制器调用MyService类的evict方法,并且在调用findOne/findAll方法时仍然可以从缓存中获益。
发布于 2017-11-07 04:28:19
除了Fabio所说的,您还可以在ehcache.xml中配置缓存限制(将其放在类路径中)。
<cache name="gendersCache"
maxEntriesLocalHeap="400"
maxEntriesLocalDisk="600"
eternal="false"
diskSpoolBufferSizeMB="20"
timeToIdleSeconds="1800"
timeToLiveSeconds="3600"
memoryStoreEvictionPolicy="LFU"
transactionalMode="off">
<persistence strategy="localTempSwap"/>
</cache>对于Springboot,在application.properties中添加以下行
spring.cache.ehcache.config=classpath:ehcache.xml对于常规的spring应用程序,在下面添加您的applicationContext.xml文件
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="/WEB-INF/ehcache.xml" p:shared="true"/> https://stackoverflow.com/questions/47124653
复制相似问题