Java缓存ehcache的使用步骤

发布时间:2021-07-06 11:13 来源:脚本之家 阅读:0 作者:彩虹咖啡 栏目: 开发技术

目录

一、pom.xml

<dependency>
		    <groupId>net.sf.ehcache</groupId>
		    <artifactId>ehcache</artifactId>
		    <version>2.10.4</version>
</dependency>

二、编写ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
 
	<cacheManagerPeerProviderFactory
		class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
		properties="peerDiscovery=automatic, multicastGroupAddress=198.1.1.1,
         multicastGroupPort=10001,
         timeToLive=1" />
 
	<cacheManagerPeerListenerFactory
		class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
		properties="port=10001,socketTimeoutMillis=60000" />
 
	<!-- 磁盘缓存位置 -->
	<diskStore path="java.io.tmpdir/anywhere" />
 
	
	<cache name="oneCache" maxElementsInMemory="1500" eternal="false"
		timeToIdleSeconds="900" timeToLiveSeconds="900" overflowToDisk="false"
		memoryStoreEvictionPolicy="LRU">
		<cacheEventListenerFactory
			class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" properties="replicateRemovals=false"/>
		<bootstrapCacheLoaderFactory
			class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory" />
	</cache>
	
</ehcache>

三、参数简介

四、Ehcache的缓存数据淘汰策略

FIFO:先进先出

LFU:最少被使用,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。

LRU:最近最少使用,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存

五、编写spring-ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
  <description>ehcache</description>
  <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
    <property name="cacheManager" ref="ehcache"/>
  </bean>
  <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="classpath:/ehcache.xml"/>
  </bean>
</beans>

六、与Spring整合,导入到spring配置文件

<import resource="classpath:/spring-ehcache.xml"/>

七、Java Source code

使用类导入:
    @Resource
    private org.springframework.cache.ehcacheEhCacheCacheManager cacheManager;

从获取cache
    Cache cache = cacheManager.getCache(“oneCache”);
存入cache
    cache.put(“key”, “value”);
从cache中获取
    ValueWrapper val = cache.get(“key”);
    String tempVal = (String)val.get();

到此这篇关于Java缓存ehcache的使用步骤的文章就介绍到这了,更多相关ehcache缓存的使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

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