【问题标题】:How to implement caching in Spring JPA如何在 Spring JPA 中实现缓存
【发布时间】:2018-04-17 21:22:18
【问题描述】:

我想使用 Ehcache 和 java 配置(不是通过 xml)在 spring jpa 存储库中实现缓存功能。但我对@cache、@caceevict、@cacheable、@caching 注释感到困惑。

1) 我想从缓存中获取数据,如果缓存中没有数据,那么应该从数据库中获取。

2) 如果我点击 /api/cacheRefresh 从控制器,它应该刷新所有表。

【问题讨论】:

  • 你有没有彻底浏览过spring docs,他们对每种类型的缓存注解都非常清楚
  • JPA 使用它自己的缓存。我怀疑在此之上添加缓存是否有任何好处。

标签: spring spring-boot spring-data-jpa


【解决方案1】:

除了 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"/> 

【讨论】:

    【解决方案2】:

    在一个典型的应用程序中,你会有这样的层:

    • 存储库,它们可以访问您的“存储”,例如 db、nosql 等,以及来自外部服务的数据(例如通过 rest 调用)
    • 服务,可能包含也可能不包含业务逻辑,并使用存储库来收集应用该业务逻辑所需的所有数据

    您通常不会将缓存放在存储库层上,而是应该在服务层上完成。因此,要回答您的问题,您应该让 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 方法时仍然可以从缓存中受益。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 2020-04-09
      • 2017-11-22
      • 1970-01-01
      • 2021-12-04
      • 2017-08-16
      • 2012-12-04
      相关资源
      最近更新 更多