spring ehcache 不工作

spring ehcache is not working

我正在尝试实现 ehcache 以获取在应用程序启动期间加载的静态数据(来自 table),但是当我再次调用数据库时,调用将转到数据库(可以参见 运行 sql 在控制台上)而不是从 ehcache 中获取值。

我的代码是:

ehcache.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd"
    updateCheck="true"
    monitoring="autodetect"
    dynamicConfig="true">

    <diskStore path="java.io.tmpdir" />

    <cache name="ObjectList"
        maxEntriesLocalHeap="10000"
        maxEntriesLocalDisk="1000"
        eternal="false"
        diskSpoolBufferSizeMB="20"
        timeToIdleSeconds="2000000" timeToLiveSeconds="900000000000"
        memoryStoreEvictionPolicy="LFU"
        transactionalMode="off">
        <persistence strategy="localTempSwap" />
    </cache>
</ehcache>

我的存储库 class 是:

public interface customRepository extends JpaRepository<Object, Long> {

  @Cacheable(value = "ObjectList", cacheManager="abclCacheManager")
  public Object findById(Long id);

  @Cacheable(value = "ObjectList", cacheManager="abclCacheManager")
  public List<Object> findAll();
}

我的 cacheInitialiser class 是:

@Configuration
@EnableCaching
@ComponentScan("com.abcl.process")
public class EhCacheConfiguration {

  @Bean("abclCacheManager")
  public CacheManager cacheManager() {
    return new EhCacheCacheManager(ehCacheCacheManager().getObject());
  }

  @Bean
  public EhCacheManagerFactoryBean ehCacheCacheManager() {
    EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
    cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
    cmfb.setShared(true);
    cmfb.setCacheManagerName("abclCacheManager");

    return cmfb;
  }

}

我正在使用以下方法测试我的这个:

public class testCache {
  doSomething() { 
    List<Object> listObject = repo.findAll();
    listObject.size();
  }

  public void getOne() { 
    Object o = repo.findById(1L);
  }
}

我可以在 getAll 方法中看到数据库命中,但我认为结果会存储在缓存中,在第二次调用中,方法 getById 不会命中数据库,但是我在第二次调用中也看到了数据库命中.

如果我遗漏了什么,有人可以提出建议吗?

当您缓存 findAll 的结果时,它会在缓存中创建一个条目,将 Spring 缓存生成的键映射到 List<Object>.它不会将 idObject.

之间每个列表元素的一个映射放入缓存中

因此,当您使用 findById(Long) 时,Spring 缓存将查找映射到 id 的缓存条目。由于找不到,它将访问数据库。

无法让 Spring 缓存为每个集合元素放置一个映射。如果这确实是您所需要的,您将不得不对其进行编码,而不是依赖于 @Cacheable 注释。