首页 文章

如何在Spring JPA中实现缓存

提问于
浏览
1

我想在Spring jpa存储库中使用带有java配置的Ehcache(而不是xml)来实现缓存功能 . 但我对@cache,@ caceevict,@ cacheable,@caching annotations感到困惑 .

1)我想从缓存中获取数据,如果数据在缓存中不可用,那么它应该从数据库中获取 .

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

2 回答

  • 1

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

    • repositories ,可以访问您的"storages",例如db,nosql等,以及来自外部服务的数据,例如通过休息调用

    • services ,它可能包含也可能不包含业务逻辑,并使用存储库来收集应用该业务逻辑所需的所有数据

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

  • 0

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

相关问题