缓存技术内部交流_02_Ehcache3 XML 配置
参考资料:
http://www.ehcache.org/documentation/3.2/getting-started.html#configuring-with-xml
http://www.ehcache.org/documentation/3.2/xml.html
示例代码:
https://github.com/gordonklg/study,cache module
A. 实例
gordon.study.cache.ehcache3.basic.XmlConfig.java
public class XmlConfig {
public static void main(String[] args) {
final URL myUrl = XmlConfig.class.getResource("/ehcache3_basic.xml");
Configuration xmlConfig = new XmlConfiguration(myUrl);
CacheManager cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig);
cacheManager.init();
Cache<String, UserModel> phoneUserCache = cacheManager.getCache("phoneUserCache", String.class, UserModel.class);
UserModel user = new UserModel("13316619988", "abc@123.com", "openid12345", "very very long user information ...");
phoneUserCache.put(user.getPhone(), user);
UserModel cached = phoneUserCache.get(user.getPhone());
System.out.println(cached.getInfo());
}
}
示例代码简单明了,没啥好说的。
ehcache3_basic.xml in src/main/resources
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns='http://www.ehcache.org/v3' xmlns:jsr107='http://www.ehcache.org/v3/jsr107'
xsi:schemaLocation="
http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.2.xsd
http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.2.xsd">
<cache-template name="userTemplate">
<key-type>java.lang.String</key-type>
<value-type>gordon.study.cache.ehcache3.basic.UserModel</value-type>
<heap unit="entries">5</heap>
</cache-template>
<cache alias="phoneUserCache" uses-template="userTemplate">
<heap unit="entries">20</heap>
</cache>
<cache alias="emailUserCache" uses-template="userTemplate" />
</config>
配置文件同样简单明了。其中 cache-template 为缓存模板,可以简化配置。