Ehcache Statistics by key

11,184

Solution 1

The EhCache Monitor gives you that type of information... http://ehcache.org/documentation/monitor.html

Programmatic access is available as follows:

    CacheManager cacheManager = CacheManager.getInstance();
    String[] cacheNames = cacheManager.getCacheNames();
    for (int i = 0; i < cacheNames.length; i++) {
        String cacheName = cacheNames[i];
        System.out.println(cacheName+" - "+ cacheManager.getCache(cacheName).getStatistics().toString());
    }

Solution 2

You can't track misses on a per-key basis because the statistics are stored on object IN the cache and if there was a miss, there would be no element in the cache to track it. But if you want a hit-count for all the keys in a cache you'd need to do something like:

public Map<Object,long> getKeyHits(Ehcache cache)
{
  Map<Object,long> hitMap = new HashMap<Object,long>();
  Map<Object,Element> allElements = cache.getAll(cache.getKeys());
  for (Object key : allElements.keySet())
  {
    hitMap.put(key, allElements.get(key).hitCount());
  }
  return hitMap;
}

If you'd rather see statistics aggregated over an entire cache (or you want to track misses), you can call getStatistics() on the cache. See http://ehcache.org/apidocs/net/sf/ehcache/Ehcache.html.

Share:
11,184

Related videos on Youtube

Kevin B
Author by

Kevin B

Updated on June 04, 2022

Comments

  • Kevin B
    Kevin B almost 2 years

    I am interested in getting statistics on the Ehcache I have running.

    I would like to see the number of hits/misses for a given key over a period of time. Perhaps in the form of a map. For example.

    For the passed hour (or however long it has been running)

    Key A had 30 hits and 2 misses
    Key B had 400 hits and 100 misses
    Key C had 2 hits and 1 misses
    Key D had 150 hits and 10 misses

    I have looked through the documentation (SampledCacheStatistics, SampledCacheStatisticsImpl, SampledCacheStatisticsWrapper, etc) and I am having a terrible time figuring this out.

    Has anyone else had experience implementing this?

    Any help or ideas on this would be MUCH appreciated!

  • Kevin M
    Kevin M over 9 years
    Too bad Terracotta doesn't provide this free anymore. You must go with their commercial product to use the ehCache monitor. Bummer
  • monzonj
    monzonj over 7 years
    This does not give you the statistics per key. Just global