如何在Spring Boot中获取Spring缓存的大小?

时间:2020-09-30 15:18:45

标签: spring spring-boot spring-cache

我有以下两种方法:

@Cacheable(cacheNames = "foos")
  public List<FooDto> getAllFoos() {
    return this.fooRepository.findAll().stream()
      .map(FooEntityDomainToDtoMapper::mapDomainToDto) // mapping entity to dto
      .collect(Collectors.toList());
  }
  
    @Cacheable(cacheNames = "foos",key = "#fooDto.Id")
  public FooDto getFooById(FooDto fooDto) {
    return this.fooRepository.findById(fooDto.getId()).stream()
      .map(FooEntityDomainToDtoMapper::mapDomainToDto) // mapping entity to dto
      .collect(Collectors.toList());
  }

当用户通过特定ID请求对象时,将在系统启动期间调用第一个getAllFoos(),并在启动系统后调用第二个。我想知道第二种方法是否会占用任何单独的缓存空间,还是只是在第一种方法获得的缓存中添加键?我想确认,即使我评论第二个getFooById()缓存的大小是否相同?有什么方法可以获取缓存的大小吗?

P.S:我们没有使用任何缓存实现,只是使用spring-boot-starter-cache

1 个答案:

答案 0 :(得分:0)

尽管没有直接方法可以查看缓存数据并获取大小,但是可以使用反射来做到这一点。这就是我所做的。

public Object getAllCache() {
 //Autowire your cache manager first and then process the request using cache manager
        ConcurrentMapCache cache = (ConcurrentMapCache) manager.getCache("yourCachename");
        Object store1 = null;
        try {
            Field store = ConcurrentMapCache.class.getDeclaredField("store");
            store.setAccessible(true);
            store1 =  store.get(cache);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return store1.toString();
    }