微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我有以下两种方法

@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

解决方法

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

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();
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。