你可以使用xml配置创建CacheManager,根据这个schema definition ( http://www.ehcache.org/documentation/3.7/xsds.html#core )

一. 配置元素

<config> 根元素

config是我们xml配置文件的根元素。它代表了CacheManager的配置。

注意:Ehcache允许创建多个CacaheManager使用相同的XML配置文件。与JSR-107 javax.cache.spi.CachingProvider相对比,Ehcache不维护已创建的CacheManager的实例。

<service>元素

service元素是CacheManager所管理服务的扩展点。

用这种方式定义的service他的生命周期和管理他的CacheManger生命周期一样。对于这样的service,当CacheManager.init被调用时会触发Service.start方法。当CacheManger.close被调用时会触发Service.stop方法。

CacaheManger管理的那些Cache可以使用这些Service的实例。

JSR-107使用XML配置的扩展点在[ http://www.ehcache.org/documentation/3.7/107.html#supplement-jsr-107-configurations ]这里有介绍。

<default-serializers>元素

default-serializers元素代表了CacheManger级别的序列化配置。它是<serializer>元素的集合,<serializer>元素包含了一个type和Serializer类的全限定名。

<default-copiers>元素

default-copiers元素代表了CacheManger级别的Copiers配置,它是<copier>元素的集合,<copier>元素包含了一个type和Copier类的全限定名。

<persistence>元素

persistence元素代表了持久化,当创建PersistentCacheManager时使用它。它包含一个数据存储到Disk时的目录。

<cache>元素

一个cache元素代表一个Cache实例,这个实例被CacheManager创建并管理。每个cache元素需要一个alias属性,根据这个alias属性去调用org.ehcache.CacheManager.getCache(String,Class<K>,Class<V>),获得相应的cache实例。也可以使用uses-template属性去引用一个<cache-template>。了解详情参见[ http://www.ehcache.org/documentation/3.7/xml.html#cache-template-elements ]

如下元素是可选的:

  • <key-type>: Cache<K,V>中K的全限定类名,默认是java.lang.Object
  • <value-type>: Cache<K,V>中V的全限定类名,默认是java.lang.Object
  • <expiry>: 控制expiry的类型和他的参数
  • <eviction-advisor>: 实现org.ehcache.config.EvictionAdvisor<K,V>类的全限定名,默认是null
  • <integration>: 用于配置cache-through模式的CacheLoaderWriter
  • <resources>: 配置层的信息和层的容量,当只是用heap层时,你可以使用<heap>元素代替它

<cache-template>元素

cache-template元素是<cache>元素的模板,它具有唯一性,可以通过name属性设置名字。cache元素通过使用uses-template属性指定cache-template的名字可以继承该模板中所有的属性值。当然<cache>也可以重写模板中的属性。

注意:Processing of cache template configurations can be triggered lazily by actions that dynamically bind new caches to existing cache templates. Errors within such templates may not be revealed until this lazy processing is triggered.

二. XML配置文件中属性替换

在XML配置文件内部可以引用java system properties值,在配置解析时这些引用会被替换为value。

使用的语法格式为${prop.name},他可以用在所有attributes和elements的值上,目前这个规则不包含用来调整大小的数字和标识符,例如cache和cache-template的名字。

注意:如果这个系统属性不存在,那么会导致配置解析失败。

一个典型的应用是在<persistence>标签中的directory属性上,配置file路径

<persistence directory="${user.home}/cache-data"/>(1)

这里的user.home将会被系统中的属性替换,比如说替换成/home/user

三. XML配置解析

如果你能通过JSP-107API获取CacheManager,当你在调用javax.cache.spi.CachingProvider.getCacheManager(java.net.URI,java.lang.ClassLoader)后,接下来的事情会自动完成。

final URL myUrl = getClass().getResource("/configs/docs/getting-started.xml"); (1)
XmlConfiguration xmlConfig = new XmlConfiguration(myUrl); (2)
CacheManager myCacheManager = CacheManagerBuilder.newCacheManager(xmlConfig); (3)
myCacheManager.init(); (4)

(1). 获取xml文件的位置

(2). 通过xml文件的url实例化一个XmlConfiguration

(3). 使用静态方法CacheManagerBuilder.newCacheManager(Configuration)创建CacheManager

(4). 在使用之前要初始化cacheManager

我们也可以使用<cache-template>来作为CacheConfigurationBuilder的配置,为了使用<cache-template>元素你需要创建一个xml文件,包含如下内容:

<cache-template name="example">
<key-type>java.lang.Long</key-type>
<value-type>java.lang.String</value-type>
<heap unit="entries">200</heap>
</cache-template>

用如下的方式创建CacheConfigurationBuilder

XmlConfiguration xmlConfiguration = new XmlConfiguration(getClass().getResource("/configs/docs/template-sample.xml"));
CacheConfigurationBuilder<Long, String> configurationBuilder = xmlConfiguration.newCacheConfigurationBuilderFromTemplate("example", Long.class, String.class); (1)
configurationBuilder = configurationBuilder.withResourcePools(ResourcePoolsBuilder.heap(1000)); (2)

(1). 创建builder,继承cache-template的属性,heap的大小为200个entry。

(2). 重写继承的属性

四. 编程的方式配置XML文件

就像根据xml文件创建cache manager一样,反向翻译也是支持的。

CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.with(CacheManagerBuilder.persistence(tmpDir.newFile("myData")))
.withCache("threeTieredCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
ResourcePoolsBuilder.newResourcePoolsBuilder()
.heap(10, EntryUnit.ENTRIES)
.offheap(1, MemoryUnit.MB)
.disk(20, MemoryUnit.MB, true))
.withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(20)))
).build(false); Configuration configuration = cacheManager.getRuntimeConfiguration();
XmlConfiguration xmlConfiguration = new XmlConfiguration(configuration); (1)
String xml = xmlConfiguration.toString(); (2)

(1). 通过CacheManager的configuration来实例化一个XmlConfiguration

(2). 通过使用toString方法来获得xml内容

不是所有的编程式的配置都可以转换成xml文件的,如果cache manager中包含了如下的内容就不可以转换:

  1. EvictionAdvisor
  2. 自定义的ExpiryPolicy,而不是从ExpiryPolicyBuilder从获取的timeToLiveExpiration或者是timeToIdleExpiration
  3. 使用实例代替他们的classes:
    a. Serializer
    b. Copier
    c. CacheLoaderWriter
    d. CacheEventListener
    e. ResilienceStrategy

五. 在一个文件中配置多个CacheManager

使用该特性最简单配置就是嵌套多个cache manager configurations在同一个xml文件中。

<multi:configurations
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns='http://www.ehcache.org/v3'
xmlns:multi='http://www.ehcache.org/v3/multi'
xsi:schemaLocation='http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd
http://www.ehcache.org/v3/multi http://www.ehcache.org/schema/ehcache-multi.xsd'> <!--1--> <multi:configuration identity="foo-manager"> <!--2-->
<config>
<cache alias="foo">
<key-type>java.lang.String</key-type>
<value-type>java.lang.String</value-type>
<resources>
<heap unit="entries">20</heap>
<offheap unit="MB">10</offheap>
</resources>
</cache>
</config>
</multi:configuration> <multi:configuration identity="bar-manager">
<config>
<cache alias="bar">
<key-type>java.lang.String</key-type>
<value-type>java.lang.String</value-type>
<resources>
<heap unit="entries">20</heap>
<offheap unit="MB">10</offheap>
</resources>
</cache>
</config>
</multi:configuration>
</multi:configurations>

(1). 最顶级的元素<configurations>包含了namespace和一些核心schema。

(2). 每个Ehcache的配置都包含在configuration标签中,并且他需要一个唯一的标识identity属性。

通过xml文档创建XmlMultiConfiguration实例。

    XmlMultiConfiguration multipleConfiguration = XmlMultiConfiguration
.from(getClass().getResource("/configs/docs/multi/multiple-managers.xml")) (1)
.build(); (2)
Configuration fooConfiguration = multipleConfiguration.configuration("foo-manager"); (3)

(1). XmlMultiConfiguration是XML文件中resource的集合

(2). 构建这个配置

(3). 可以通过他们的identites获取Configuration实例

多个CacheManager的变体

对于给定的manager,可以通过包含一系列<variant>标签来提供变体配置,每个标签中都需要一个type属性。

<multi:configurations
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns='http://www.ehcache.org/v3'
xmlns:multi='http://www.ehcache.org/v3/multi'
xsi:schemaLocation='http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd
http://www.ehcache.org/v3/multi http://www.ehcache.org/schema/ehcache-multi.xsd'> <!-- tag::variants[] -->
<multi:configuration identity="foo-manager">
<multi:variant type="heap">
<config>
<cache alias="foo">
<key-type>java.lang.String</key-type>
<value-type>java.lang.String</value-type>
<resources>
<heap unit="entries">1000</heap>
</resources>
</cache>
</config>
</multi:variant>
<multi:variant type="offheap">
<config>
<cache alias="foo">
<key-type>java.lang.String</key-type>
<value-type>java.lang.String</value-type>
<resources>
<heap unit="entries">1000</heap>
<offheap unit="MB">128</offheap>
</resources>
</cache>
</config>
</multi:variant>
</multi:configuration>
<!-- end::variants[] --> <multi:configuration identity="bar-manager">
<config>
<cache alias="bar">
<key-type>java.lang.String</key-type>
<value-type>java.lang.String</value-type>
<resources>
<heap unit="entries">1000</heap>
</resources>
</cache>
</config>
</multi:configuration>
</multi:configurations>

可以通过指定variant和identity来获取一个cache configuration

 Configuration fooConfiguration = variantConfiguration.configuration("foo-manager", "offheap"); 

上面的仅仅是一个例子,variant的类型可以有很多种:development vs production,clustered vs unclustered,red vs blue等等。

注意:当Configurations中有多个variant时必须有一个variant指定type,否则在获取时会抛出IllegalStateException异常。当Configurations中没有多个variants时将始终为所有的请求返回单个的配置。

获取多个CacheManager

通过遍历identites,可以从XmlMultiConfiguration中获取多个CacheManager

    Map<String, Configuration> allConfigurations = multipleConfiguration.identities().stream() // <1>
.collect(Collectors.toMap(i -> i, i -> multipleConfiguration.configuration(i))); // <2>
Map<String, Configuration> offheapConfigurations = variantConfiguration.identities().stream()
.collect(Collectors.toMap(i -> i, i -> variantConfiguration.configuration(i, "offheap"))); // <3>

(1). 多个配置中identites集合的stream

(2). 映射每个identity到他的唯一配置上

(3). 另一种选择为映射每个identity到指定的variant配置上

构建多个配置的XML

XmlMultiConfiguration实例可以被组装和修改通过使用相关的API,之前解析XML Multi-Configuration的例子仅仅是一个简单的调用。

Configurations可以从头被构建,像下面那样:

    XmlMultiConfiguration multiConfiguration = XmlMultiConfiguration.fromNothing() // <1>
.withManager("bar", barConfiguration) // <2>
.withManager("foo").variant("heap", heapConfiguration).variant("offheap", offheapConfiguration) // <3>
.build(); // <4>

(1). 创建一个空的XmlMultiConfiguration

(2). 添加configuration,不带variants

(3). 添加一个configuration带两个不同的variants:heap和offheap

(4). 构建最终的configuration实例

他们也可以通过已经存在的配置中构建

    XmlMultiConfiguration modified = XmlMultiConfiguration.from(multiConfiguration) // <1>
.withManager("foo") // <2>
.build();

(1). multiConfiguration是一个已经存在配置

(2). Remove the configuration with identity "foo"

以xml的格式获取一个已经构建的multi-configuration

    String xmlString = multiConfiguration.asRenderedDocument(); // <1>
Document xmlDocument = multiConfiguration.asDocument(); // <2>

(1). 以字符串的形式获取xml

(2). 以DOM的形式获取xml

Ehcache 3.7文档—基础篇—XML Configuration的更多相关文章

  1. Ehcache 3.7文档—基础篇—JCache aka JSR-107

    一. 概述JCache Java临时缓存API(JSR-107),也被称为JCache,它是一个规范在javax.cache.API中定义的.该规范是在Java Community Process下开 ...

  2. Ehcache 3.7文档—基础篇—GettingStarted

    为了使用Ehcache,你需要配置CacheManager和Cache,有两种方式可以配置java编程配置或者XML文件配置 一. 通过java编程配置 CacheManager cacheManag ...

  3. Ehcache 3.7文档—基础篇—Tiering Options

    Ehcache支持分层缓存的概念,这节主要介绍不同的配置选项,同时也解释了规则和最佳实践. 一. 数据缓存到堆外 当在cache中除了有heap层之外,有一些需要注意的: 添加一个key-value到 ...

  4. Mongoose学习参考文档——基础篇

    Mongoose学习参考文档 前言:本学习参考文档仅供参考,如有问题,师请雅正 一.快速通道 1.1 名词解释 Schema : 一种以文件形式存储的数据库模型骨架,不具备数据库的操作能力 Model ...

  5. XWPFDocument创建和读取Office Word文档基础篇(一)

    注:有不正确的地方还望大神能够指出,抱拳了 老铁!   参考API:http://poi.apache.org/apidocs/org/apache/poi/xwpf/usermodel/XWPFDo ...

  6. java 使用 POI 操作 XWPFDocumen 创建和读取 Office Word 文档基础篇

    注:有不正确的地方还望大神能够指出,抱拳了 老铁! 参考 API:http://poi.apache.org/apidocs/org/apache/poi/xwpf/usermodel/XWPFDoc ...

  7. TypeScript学习文档-基础篇(完结)

    目录 TypeScript学习第一章:TypeScript初识 1.1 TypeScript学习初见 1.2 TypeScript介绍 1.3 JS .TS 和 ES之间的关系 1.4 TS的竞争者有 ...

  8. HTML文档基础

    一.HTML(Hyper Text Markup Language超文本标记语言)是一种用来制作超文本文档的简单标记语言,HTML在正文的文本中编写各种标记,通过Web浏览器进行编译和运行才干正确显示 ...

  9. 【XML】利用Dom4j读取XML文档以及写入XML文档

    Dom4j简介 dom4j是一个Java的XML API,是jdom的升级品,用来读写XML文件的.dom4j是一个十分优秀的JavaXML API,具有性能优异.功能强大和极其易使用的特点,它的性能 ...

随机推荐

  1. input(type="checkbox"|type="radio")+jquery使用

    1.用.is(":checked")判断input是否为选中状态 例: var value=$(this).is(":checked"); localStora ...

  2. 学习熟悉箭头函数, 类, 模板字面量, let和const声明

    箭头函数:https://blog.csdn.net/qq_30100043/article/details/53396517 类:https://blog.csdn.net/pcaxb/articl ...

  3. Ch02 课堂作业

    测试一:运行结果: 测试二:运行结果: 测试三:运行结果:

  4. Ansible之Playbook详解、案例

    什么是playbook playbooks是一个不同于使用Ansible命令行执行方式的模式,其功能更强大灵活.简单来说,playbook是一个非常简单的配置管理和多主机部署系统,不同于任何已经存在的 ...

  5. MySql常见的数据类型

    ⒈整型 名称 字节数 tinyint 1 smallint 2 mediumint 3 int/integer 4 bigint 8 特点: 1.如果不设置无符号还是有符号,默认是有符号,如果想设置无 ...

  6. Spring注解@Configuration和Java Config

    1.从Spring 3起,JavaConfig功能已经包含在Spring核心模块,它允许开发者将bean定义和在Spring配置XML文件到Java类中.但是,仍然允许使用经典的XML方式来定义bea ...

  7. redis 数据结构及应用场景

    1. String 常用命令: get.set.incr.decr.mget等 应用场景: String是最常用的数据类型,普通的key/value都可以归为此类,value其实不仅是String,也 ...

  8. 022_word中如何正确的使用正则表达式进行搜索

    一.word中正则表达式详解 https://www3.ntu.edu.sg/home/ehchua/programming/howto/PowerUser_MSOffice.html 实战举例: ( ...

  9. 帆软报表(finereport) 动态报表

    动态表实现了不同的人根据需要选择不同的表进行查看,从而提高查询效率 在定义数据集时,通过if函数来判断参数的值从而来实现调用不同的数据表 如直接将SQL语句定义成:SELECT * FROM ${if ...

  10. 【原创】大叔问题定位分享(19)spark task在executors上分布不均

    最近提交一个spark应用之后发现执行非常慢,点开spark web ui之后发现卡在一个job的一个stage上,这个stage有100000个task,但是绝大部分task都分配到两个execut ...