我在一些项目中使用了core.cache。这是一个很棒的库,我非常喜欢。它只是缺少统计信息,这样我可以根据某些统计数据调整缓存的尺寸。我已经决定编写一个自定义的缓存实现,以允许获取缓存的命中/未命中统计信息。最初,这是一个独立的项目,但后来我意识到我需要修改core.cache本身的一个更改,我不能很好地绕过它。所以这里是如何添加具有统计功能的缓存实现的补丁。
快速演示
{code:none}
(require '[clojure.core.cache :as core.cache]
'[clojure.core.cache.stats :as ccs]
'[clojure.core.cache.stats.counters :as ccs.counters])
(def cache (-> {} core.cache/lru-cache-factory ccs/measured-cache))
(ccs/stats cache) ; {:hit 0, :miss 0, :request 0, :hit-ratio 1.0, :miss-ratio 1.0}
(def cache (assoc cache :foo "bar"))
(ccs/stats cache) ; {:hit 0, :miss 1, :request 1, :hit-ratio 0.0, :miss-ratio 1.0}
(get cache :foo) ; "bar"
(get cache :foo) ; "bar"
(ccs/stats cache) ; {:hit 2, :miss 1, :request 3, :hit-ratio 0.6666666666666666, :miss-ratio 0.3333333333333333}
新增功能
* providing a namespace called core.cache.stats, which provides MeasuredCache that implements CacheProtocol and a function called measured-cache to instantiate it. MeasuredCache also implements MeasuredCacheProtocol which has only one responsibility - to return hit/miss statistics snapshot.
* providing a namespace called core.cache.stats.counters which provides a protocol called StatsCounterProtocol that allows for implementing hit/miss counters. There are already two implementions available: one is based on a long wrapped in atom, and the other (used by default) is based on LongAdder.
* There are tests available for all methods that could be invoked.
注意事项(不分先后)
* LongAdderStatsCounter introduces a hard dependency on the LongAdder class which was added in Java 1.8. Although I've tried to make it optional, I failed as it seems
here。
* I have modified the defcache macro (all tests pass) so that I can actually override definitions.
合并前要完成的事情
* If you like the idea, I'll add more documentation (maybe I should have started with this one so it has a higher chance of being accepted?)
* Reforge the code (I'm greatly not an expert in Clojure), naming, and namespaces
感谢提前反馈