Alain P
Alain P

Reputation: 1343

How can I activate JMX for Caffeine cache

I was looking at this SO question, but here I only want Caffeine to start reporting to JMX.

I have added an application.conf file as such and referenced it via -Dconfig.file:

caffeine.jcache {
  # A named cache is configured by nesting a new definition under the caffeine.jcache namespace. The
  # per-cache configuration is overlaid on top of the default configuration.
  default {
    # The monitoring configuration
    monitoring {
      # If JCache statistics should be recorded and externalized via JMX
      statistics = true

      # If the configuration should be externalized via JMX
      management = true
    }
}

It is not working, but I suspect it might be related to jcache, but not sure what is the expected way to implement this basic monitoring.

Upvotes: 1

Views: 877

Answers (1)

Ben Manes
Ben Manes

Reputation: 9621

The cache instance is registered with the MBean server when it is instantiated by the CacheManager. The following test uses the programmatic api for test simplicity.

public final class JmxTest {

  @Test
  public void jmx() throws MalformedObjectNameException {
    var config = new CaffeineConfiguration<>();
    config.setManagementEnabled(true);
    config.setStatisticsEnabled(true);

    var manager = Caching.getCachingProvider().getCacheManager();
    var cache = manager.createCache("jmx", config);
    cache.put(1, 2);

    var server = ManagementFactory.getPlatformMBeanServer();
    String name = String.format("javax.cache:type=%s,CacheManager=%s,Cache=%s",
        "CacheStatistics", manager.getURI().toString(), cache.getName());
    var stats = JMX.newMBeanProxy(server, new ObjectName(name), CacheStatisticsMXBean.class);
    assertThat(stats.getCachePuts()).isEqualTo(1);
  }
}

If you do not need JCache for an integration then you will likely prefer to use the native APIs and metrics library. It is supported by Micrometer, Dropwizard Metrics, and the Prometheus client. While JCache is great for framework integrations, its api is rigid and cause surprising performance issues.

Upvotes: 1

Related Questions