Friday, 2 February 2018

A different kind of template: wildcards

Infinispan's configuration templates are an extremely flexible way to create multiple caches using the same configuration. Configuration inheritance works by explicitly declaring the configuration a specific cache should use.

This works fine when you know the caches you are going to use upfront, but in more dynamic scenarios, this might not be possible. Additionally, if you are using the JCache API, there is no way for you to specify the configuration template you want to use.

Infinispan 9.2 introduces an alternative way to apply templates to caches: wildcards. By creating a template with a wildcard in its name, e.g. `basecache*`, any cache whose name matches the template name will inherit that configuration.

Let's show an example:

<infinispan>
<cache-container>
<local-cache-configuration name="basecache*">
<expiration interval="10500" lifespan="11" max-idle="11"/>
</local-cache-configuration>
<local-cache name="basecache-1"/>
<local-cache name="basecache-2"/>
</cache-container>
</infinispan>
view raw wildcard.xml hosted with ❤ by GitHub
Above, caches `basecache-1` and `basecache-2` will use the `basecache*` configuration. This behaviour also applies when retrieving caches programmatically:

EmbeddedCacheManager cm = new DefaultCacheManager();
cm.defineConfiguration("basecache*", new ConfigurationBuilder()
.expiration().lifespan(10)
.build());
Cache<Object, Object> basecache1 = cm.getCache("basecache1");

When using the JCache API, using the XML file above and the following code will achieve the same result:

CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager cacheManager = cachingProvider.getCacheManager(
this.getClass().getResource("wildcard.xml").toURI(),
this.getClass().getClassLoader()
);
Cache<Object, Object> basiccache1 = cacheManager.createCache(
"basiccache1",
new MutableConfiguration<>()
);

NOTE: If a cache name matches multiple wildcards, i.e. it is ambiguous, an exception will be thrown.

I will be introducing other new features that Infinispan 9.2 brings to cache configuration in an upcoming blog post. Stay tuned !

No comments:

Post a Comment