Configuring Storage Tiers using XML
As an alternative to programmatic configuration, a
CacheManager can also be configured using XML, as
illustrated in this example:
<config>
<cache alias="foo"> <!--1-->
<key-type>java.lang.String</key-type> <!--2-->
<resources>
<heap unit="entries">2000</heap> <!--3-->
<offheap unit="MB">500</offheap> <!--4-->
</resources>
</cache>
<cache-template name="myDefaults"> <!--5-->
<key-type>java.lang.Long</key-type>
<value-type>java.lang.String</value-type>
<heap unit="entries">200</heap>
</cache-template>
<cache alias="bar" uses-template="myDefaults"> <!--6-->
<key-type>java.lang.Number</key-type>
</cache>
<cache alias="simpleCache" uses-template="myDefaults" /> <!--7-->
</config>
-
Declares a
Cachealiased tofoo. -
The keys of
fooare declared as typeString.Since the value type is not specified, the values will be of type
java.lang.Object. -
foois declared to hold up to 2,000 entries on heap ... -
... as well as up to 500 MB of off-heap memory before the
Cachestarts evicting -
<cache-template>elements create an abstract configuration that can be extended by further<cache>configurations -
baris an example for such aCache.baruses the<cache-template>namedmyDefaultsand overrides itskey-typeto a wider type. -
simpleCacheis another suchCache.simpleCacheusesmyDefaultsconfiguration for its soleCacheConfiguration.
The schema and format of the XML is explained in detail in the following section The XML Schema Definition.
The type
XmlConfiguration allows for parsing an XML
configuration:
URL myUrl = getClass().getResource("/my-config.xml"); // <1>
Configuration xmlConfig = new XmlConfiguration(myUrl); // <2>
CacheManager myCacheManager =
CacheManagerBuilder.newCacheManager(xmlConfig); // <3>
As the steps are ...
-
Obtain a URL to the location of the XML file.
-
Instantiate an
XmlConfigurationpassing the URL of the XML file. -
Use the static
org.ehcache.config.builders.CacheManagerBuilder .newCacheManager(org.ehcache.config.Configuration)creates the
CacheManagerinstance using theConfigurationfrom theXmlConfiguration.