Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, using Ehcache, you can configure your caches and retrieve their sizes by Java code only (no XML config). The exact way to integrate everything depends on your specific architecture; I'm going to assume Jersey for doing API stuff and Guice for dependency injection.</p> <p><strong>Defining your cache</strong></p> <p>Make your cache manager available via dependency injection. This can be done via a Guice module:</p> <pre><code>@Provides @Singleton CacheManager provideCacheManager() { CacheManager cacheManager = CacheManager.create(); /* very basic cache configuration */ CacheConfiguration config = new CacheConfiguration("mycache", 100) .timeToLiveSeconds(60) .timeToIdleSeconds(30) .statistics(true); Cache myCache = new Cache(config); cacheManager.addCacheIfAbsent(myCache); return cacheManager; } </code></pre> <p>Notice that statistics is turned on for <code>mycache</code>.</p> <p>Again, using your cache can be done entirely in Java code but depends on your architecture and design. Typically I do this using method interception (via AOP) but that's another topic.</p> <p><strong>Fetch cache stats via REST API</strong></p> <p>Given your <code>CacheManager</code> is available via dependency injection you can then wire it up to a REST endpoint and allow access to cache statistics:</p> <pre><code>@Path("stats") @Produces("text/plain") public class StatsResource { @Inject private CacheManager cacheManager; @GET public String stats() { StringBuffer sb = StringBuffer(); /* get stats for all known caches */ for (String name : cacheManager.getCacheNames()) { Cache cache = cacheManager.getCache(name); Statistics stats = cache.getStatistics(); sb.append(String.format("%s: %s objects, %s hits, %s misses\n", name, stats.getObjectCount(), stats.getCacheHits(), stats.getCacheMisses() )); } return sb.toString(); } } </code></pre> <p>Now you can fetch information about your caches by REST call:</p> <pre><code>GET /stats HTTP/1.1 200 OK Content-Type: text/plain; charset=utf-8 mycache: 8 objects, 59 hits, 12 misses </code></pre> <p><strong>What about JMX?</strong></p> <p>Ehcache makes it easy to register your cache manger with an MBean server. It can be done in Java code. Update your Guice module, registering your <code>cacheManager</code> to the system <code>MBeanServer</code>:</p> <pre><code>MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); ManagementService.registerMBeans(cacheManager, mBeanServer, false, false, false, true); </code></pre> <p>Now you can attach JConsole to your Java process and find your cache statistics in the MBean <code>net.sf.ehcache.CacheStatistics</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload