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

扩展 Spring Cache Interceptor 以收集自定义指标

如何解决扩展 Spring Cache Interceptor 以收集自定义指标

我正在尝试详细收集缓存指标,例如将它们捕获为事件;对象从缓存中命中,或者是未命中,花费了 X 毫秒,而不仅仅是聚合指标。由于 Spring Cache 抽象已经足够好,我以为我会找到诸如拦截器或过滤器之类的东西,但似乎没有。一个人如何去实现一个 CacheManager 没有他们自己?作为参考,我将 Redis 缓存与 Lettuce 客户端一起使用,但更希望缓存抽象能够在一个中心位置保留并捕获缓存事件。

  • 作为 Spring 的新手,我什至不确定什么是最好的方法。我尝试创建我的 CacheManager 包装 redis 一个,但不确定它如何使用自动配置
  • 我自己的缓存管理器只是代理对包装好的所有调用,但它不知道是缓存命中还是未命中,即使缓存为空,实际方法调用也会调用它们。

解决方法

您在寻找RedisCache.getStatistics吗?

它返回 CacheStatistics

public interface CacheStatistics {

    /**
     * @return the name of the {@link RedisCache}.
     */
    String getCacheName();

    /**
     * @return number of put operations on the cache.
     */
    long getPuts();

    /**
     * @return the total number of get operations including both {@link #getHits() hits} and {@link #getMisses() misses}.
     */
    long getGets();

    /**
     * @return the number of cache get hits.
     */
    long getHits();

    /**
     * @return number of cache get misses.
     */
    long getMisses();

    /**
     * @return the number of {@link #getGets() gets} that have not yet been answered (neither {@link #getHits() hit} nor
     *         {@link #getMisses() miss}).
     */
    default long getPending() {
        return getGets() - (getHits() + getMisses());
    }

    /**
     * @return number of cache removals.
     */
    long getDeletes();

    /**
     * @param unit the time unit to report the lock wait duration.
     * @return lock duration using the given {@link TimeUnit} if the cache is configured to use locking.
     */
    long getLockWaitDuration(TimeUnit unit);

    /**
     * @return initial point in time when started statistics capturing.
     */
    Instant getSince();

    /**
     * @return instantaneous point in time of last statistics counter reset. Equals {@link #getSince()} if never reset.
     */
    Instant getLastReset();

    /**
     * @return the statistics time.
     */
    default Instant getTime() {
        return Instant.now();
    }
}
,

Lettuce 似乎没有提供测量缓存命中/未命中的可用性。
Lettuce 有一些内置指标,例如直方图或延迟。 A link to the wiki

您可以尝试从 redis 本身获取一些指标。看看redis-docs
在那里您可以获得更多数据,例如 read/write hit/missevicted_objects

总而言之:我认为对象级指标(=每个键指标?)并没有真正的帮助。您想知道 object-id-abcobject-id-def 的速度有多快吗?

但如果您真的需要:您可以使用自定义实现(RedisClient 或覆盖某些方法)自己将 proxy-pattern 定义为 bean。然后你就可以测量时间了。
我认为没有办法从 redis 获取缓存命中/未命中。也许您会在 lettuce-github-repo 和/或 redis-api 中找到一些东西。
您可以尝试使用执行时间将其存档(当获取值需要很长时间时,它可能不在缓存中),但这非常不稳定,您会得到很多误报。


编辑

作为另一个想法:在您的代理中,您可以存储请求密钥的频率的指标(它应该作为时间单位来衡量,如 requests/hour)。结合您接近 cache hit/miss 指标的执行时间。

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