Does Hazelcast honor a default cache configuration

2019-07-13 16:09发布

问题:

In the hazelcast documentation there are a few brief references to a cache named "default" - for instance, here: http://docs.hazelcast.org/docs/3.6/manual/html-single/index.html#jcache-declarative-configuration

Later, there is another mention of cache default configuration here: http://docs.hazelcast.org/docs/3.6/manual/html-single/index.html#icache-configuration

What I would like is to be able to configure "default" settings that are inherited when caches are created. For instance, given the following configuration snippet:

<cache name="default">
  <statistics-enabled>true</statistics-enabled>
  <management-enabled>true</management-enabled>
  <expiry-policy-factory>
    <timed-expiry-policy-factory expiry-policy-type="ACCESSED" time-unit="MINUTES" duration-amount="2"/>
  </expiry-policy-factory>
</cache>

I'd like for the following test to pass:

@Test
public void defaultCacheSettingsTest() throws Exception {
  CacheManager cacheManager = underTest.get();
  Cache cache = cacheManager.createCache("foo", new MutableConfiguration<>());
  CompleteConfiguration cacheConfig = (CompleteConfiguration) cache.getConfiguration(CompleteConfiguration.class);
  assertThat(cacheConfig.isManagementEnabled(), is(true));
  assertThat(cacheConfig.isStatisticsEnabled(), is(true));
  assertThat(cacheConfig.getExpiryPolicyFactory(),
    is(AccessedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 2l)))
  );
}

Ehcache has a "templating" mechanism and I am hoping that I can get a similar behavior.

回答1:

Hazelcast supports configuration with wildcards. You can use <cache name="*"> for all Caches to share the same configuration, or apply other patterns to group Cache configurations as you wish.

Note that since you already use Hazelcast declarative configuration to configure your Caches, you should use CacheManager.getCache instead of createCache to obtain the Cache instance: Caches created with CacheManager.createCache(..., Configuration) disregard the declarative configuration since they are configured explicitly with the Configuration passed as argument.