当前位置: 移动技术网 > IT编程>开发语言>Java > Ehcache 3.7文档—基础篇—XML Configuration

Ehcache 3.7文档—基础篇—XML Configuration

2019年03月25日  | 移动技术网IT编程  | 我要评论

你可以使用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

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网