如何在Spring JPA中实现缓存

如何在Spring JPA中实现缓存,spring,spring-boot,spring-data-jpa,Spring,Spring Boot,Spring Data Jpa,我想在SpringJPA存储库中使用Ehcache和java配置(而不是xml)实现缓存功能。但我对@cache、@caceevict、@cacheable、@cacheannotation感到困惑 1) 我想从缓存中获取数据,若缓存中并没有数据,那个么应该从数据库中获取数据 2) 在控制器中,如果我点击/api/cacheRefresh,它将刷新所有表。在典型的应用程序中,您将拥有如下层: 存储库,它可以访问您的“存储”,例如db、nosql等,以及来自外部服务的数据,例如通过rest调用

我想在SpringJPA存储库中使用Ehcache和java配置(而不是xml)实现缓存功能。但我对@cache、@caceevict、@cacheable、@cacheannotation感到困惑

1) 我想从缓存中获取数据,若缓存中并没有数据,那个么应该从数据库中获取数据


2) 在控制器中,如果我点击/api/cacheRefresh,它将刷新所有表。

在典型的应用程序中,您将拥有如下层:

  • 存储库,它可以访问您的“存储”,例如db、nosql等,以及来自外部服务的数据,例如通过rest调用
  • 服务,可能包含也可能不包含业务逻辑,并使用存储库收集应用该业务逻辑所需的所有数据
您通常不会将缓存放在存储库层,而是应该放在服务层。因此,为了回答您的问题,您应该让JPA存储库尽可能干净,并在访问存储库的服务上添加
@Cacheable
/
@cacheexecute
注释,例如:

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{
私有最终MyRepository存储库;
公共MyService(MyRepository存储库){
this.repository=存储库;
}
@可缓存
公共MyItem findOne(长id){
返回repository.findOne(id);
}
@可缓存
公共列表findAll(){
返回repository.findAll();
}
@缓存逐出
公共无效驱逐(){
}
}

最终,当您需要刷新缓存时,您可以从控制器调用
MyService
类的
execute
方法,当您调用
findOne
/
findAll
方法时,仍然可以从缓存中获益。

除了Fabio所说的之外,您还可以在ehcache.xml中配置缓存限制(把这个放在类路径中)

对于常规spring应用程序,请在下面一行添加applicationContext.xml文件

<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="/WEB-INF/ehcache.xml" p:shared="true"/> 


您是否仔细阅读了spring文档,对于cachingJPA的每种注释类型都非常清楚,它们都使用自己的缓存。我怀疑在上面添加缓存是否有任何好处。
 spring.cache.ehcache.config=classpath:ehcache.xml
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="/WEB-INF/ehcache.xml" p:shared="true"/>