温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用Ehcache

发布时间:2021-11-16 15:07:54 来源:亿速云 阅读:167 作者:iii 栏目:大数据

这篇文章主要介绍“如何使用Ehcache”,在日常操作中,相信很多人在如何使用Ehcache问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何使用Ehcache”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

一、简介

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。

二、简单使用(以3版本为例)

1、编程式

/**
 *  等价于
 *  <cache alias="preConfigured">
 *    <key-type>java.lang.Long</key-type>
 *    <value-type>java.lang.String</value-type>
 *    <resources>
 *	    <heap unit="entries">200</heap>
 *    </resources>
 *  </cache>
 * @author luther
 * @time 2019年7月12日  上午10:33:22
 */
@Test
public void testHelloWorld() {
	CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder
			.newCacheConfigurationBuilder(long.class, String.class, ResourcePoolsBuilder.heap(100)).build();
	CacheManagerBuilder<CacheManager> cacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
	// 将CacheManager名定义为preConfigured
	cacheManagerBuilder.withCache("preConfigured", cacheConfiguration);
	// 创建CacheManager实例
	CacheManager cacheManager = cacheManagerBuilder.build();
	// 初始化CacheManager实例
	cacheManager.init();
	// 在CacheManager中创建名为myCache的缓存对象
	Cache<Long, String> myCache = cacheManager.createCache("myCache", CacheConfigurationBuilder
			.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(1)).build());
	// 往myCache缓存中放入键为1L,值为da one!的条目
	myCache.put(1L, "da one!");
	// 通过键获取值
	String value = myCache.get(1L);
	// 展示值
	System.out.println(value);
	// 移除preConfigured缓存管理器
	cacheManager.removeCache("preConfigured"); 
	// 关闭缓存
	cacheManager.close(); 
}

2、xml配置方式

/**
 * 演示加载xml配置 
 * @author luther
 * @time 2019年7月12日  上午10:57:27
 */
@Test
public void testXml() {
	XmlConfiguration xmlConfig = new XmlConfiguration(Thread.currentThread()
			.getContextClassLoader().getResource("ehcache3.xml")); 
	CacheManager cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig); 
	cacheManager.init();
	// 在CacheManager中创建名为myCache的缓存对象
	Cache<Long, String> myCache = cacheManager.createCache("myCache", CacheConfigurationBuilder
			.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(1)).build());
	// 往myCache缓存中放入键为1L,值为da one!的条目
	myCache.put(1L, "da one!");
	// 通过键获取值
	String value = myCache.get(1L);
	// 展示值
	System.out.println(value);
	// 移除preConfigured缓存管理器
	cacheManager.removeCache("preConfigured"); 
	// 关闭缓存
	cacheManager.close(); 
}

配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<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">

	<cache alias="preConfigured">
		<key-type>java.lang.Long</key-type>
		<value-type>java.lang.String</value-type>
		<resources>
			<heap unit="entries">200</heap>
		</resources>
	</cache>

</config>	

三、配置文件详解

EhCache分2和3版本,而2版本和3版本的XML配置文件有所出入。
其中2版本的配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache
        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
        xmlns='http://www.ehcache.org/v32'
        xsi:schemaLocation="http://www.ehcache.org/v2 http://ehcache.org/ehcache.xsd">
        
  <!-- 指定数据保存在硬盘的地址 -->
  <diskStore path="java.io.tmpdir"/>
  <!-- 
    可配置路径有:
    user.home(用户的家目录)
    user.dir(用户当前的工作目录)
    java.io.tmpdir(默认的临时目录)
    ehcache.disk.store.dir(ehcache的配置目录)
    绝对路径(如:d:\\ehcache) 
  -->
  <!-- 指定默认使用的cache -->
  <defaultCache
    <!-- 清理保存在磁盘上的过期缓存项目的线程的启动时间间隔,默认120秒。 -->
    diskExpiryThreadIntervalSeconds="120"
    <!-- 设置元素不永远存储 -->
    eternal="false"
    <!-- 磁盘中的最大对象数,默认为0不限制 -->
    maxEntriesLocalDisk="0"
    <!-- 设置缓存在本地内存中最大缓存项数量,0没有限制 -->
    maxEntriesLocalHeap="0"
    <!--  
      内存回收策略(当缓存项达到maxEntriesLocalHeap限制时,剔除缓存项的策略),
      默认回收策略是:LRU最近最少使用Least Recently Used,
      其他策略有:先进先出First In First Out,Less Frequently Used使用频率最低
    -->
    memoryStoreEvictionPolicy="LRU"
    <!-- 设置活动过期时间为1小时 -->
    timeToIdleSeconds="3600"
    <!-- 设置过期时间为永久 -->
    timeToLiveSeconds="0"
    <!-- 是否保存至硬盘 -->
    overflowToDisk="false"
    <!-- 当缓存项被读出时,是否返回一份它的拷贝(返回对象是缓存中对象的拷贝)。默认fasle。 -->
    copyOnRead="true"
    <!-- 当缓存项被写入时,是否写入一份它的拷贝(写入缓存的是写入对象的拷贝)。默认false -->
    copyOnWrite="true"
    <!-- 是否收集统计信息,默认为false,不收集 -->
    statistics="true">
    <!-- 指定拷贝的策略 -->
    <copyStrategy class="net.sf.ehcache.store.compound.ReadWriteSerializationCopyStrategy"/>
    <!-- 指定持久化策略 -->
    <persistence strategy="none"></persistence>
    <!-- 
      可配置strategy有:
      localRestartable(复制所有缓存项到硬盘,仅适用于企业ehcache用户)
      ocalTempSwap(当缓存空间满时,缓存到硬盘)
      none(不缓存到硬盘)
      distributed(需要在配置terracotta的情况下使用,不适用于单实例)
    -->
  </defaultCache>
</ehcache>

如果觉的不够详细,可以参考官方给的2版本的XML详解

3版本为:

<?xml version="1.0" encoding="UTF-8"?>
<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">

  <!-- cache配置模板,可以通过uses-template被其它配置继承 -->
  <cache-template name="template">
    <!-- 指定键的类型,默认为java.lang.Object serializer:定义序列化的方式 copier:定义用于复制类型实例的协定 -->
    <key-type
      serializer="org.ehcache.impl.serialization.PlainJavaSerializer"
      copier="org.ehcache.impl.copy.SerializingCopier">java.lang.String</key-type>
    <!-- 指定值的类型,默认为java.lang.Object -->
    <value-type>java.lang.String</value-type>
    <!-- 定义过期失效机制 -->
    <expiry>
      <!-- 自定义的时间过期类全路径名,需要实现ExpiryPolicy接口 -->
      <class>com.luther.expiryPolicy.MyExpiryPolicy</class>
      <!-- 意味着缓存内容不会过期 -->
      <none />
      <!-- TimeToIdleExpiryPolicy用于设置对象在cache中的最大闲置时间(访问该对象时间就会重置) -->
      <tti>3600</tti>
      <!-- TimeToLiveExpiryPolicy用于设置对象在cache中的最大存活时间(不管有没有访问,到时即失效) -->
      <ttl>0</ttl>
    </expiry>
    <resources>
      <!-- 硬盘 -->
      <disk persistent="true" unit="MB">20</disk>
      <!-- 堆 -->
      <heap unit="entries">200</heap>
      <!-- 非堆 -->
      <offheap unit="MB" xsi:type="memory-type"></offheap>
    </resources>
  </cache-template>
</config>	

到此,关于“如何使用Ehcache”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI