最近開始學習使用Ehcache, 3.4的文檔實在過於簡單,尤爲是對於XML配置,例子太少。相對於硬編碼,我更偏心靈活的XML配置,爲了實現xml配置,摸索了兩天,終於運行成功。java
ehcache.xml文件:緩存
<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://www.ehcache.org/v3' xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd"> <persistence directory="d:\\mycache"/> <cache alias="foo"> <key-type>java.lang.String</key-type> <value-type>java.lang.String</value-type> <heap unit="entries">200</heap> </cache> <cache-template name="securityObjTemplate"> <key-type>java.lang.String</key-type> <value-type>java.lang.String</value-type> <resources> <heap unit="entries">2000</heap> <offheap unit="MB">500</offheap> <disk persistent="true" unit="MB">1000</disk> </resources> </cache-template> <!-- 緩存行情數據 --> <cache alias="hq_quote11" uses-template="securityObjTemplate"> <key-type>java.lang.String</key-type> <value-type>java.lang.String</value-type> </cache> <cache alias="last_hq_quote" uses-template="securityObjTemplate"> </cache> </config>
java代碼以下:學習
CacheConfigurationBuilder<String, String> securityConfigBuilder = xmlConfiguration.newCacheConfigurationBuilderFromTemplate("securityObjTemplate", String.class, String.class); CacheManagerBuilder<CacheManager> cmb = CacheManagerBuilder.newCacheManagerBuilder(); for(ServiceCreationConfiguration<?> scc: xmlConfiguration.getServiceCreationConfigurations()) { if(scc instanceof CacheManagerConfiguration) { cmb = cmb.with((CacheManagerConfiguration)scc); } } CacheManager securityCacheManager = cmb.build(true); Cache cache = securityCacheManager.createCache(key, securityConfigBuilder);