1. 添加pom.xml中引入依赖
<!-- ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.3<</version>
</dependency>
2.创建ehcache.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false">
<!-- 磁盘缓存位置 -->
<diskStore path="C:/ehcache" />
<!-- Cluster localhost setting -->
<!-- add-end-Author:Roy_Carroll Date:20180510 for: 解决 ehcache空指针异常 -->
<cacheManagerPeerProviderFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1,
multicastGroupPort=4446, timeToLive=32"/>
<!-- add-end-Author:Roy_Carroll Date:20180510 for:解决 ehcache空指针异常 -->
<cacheManagerPeerListenerFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
properties="hostName=localhost, port=40001,socketTimeoutMillis=2000" />
<cache name="dictCache" maxElementsInMemory="500" overflowToDisk="true"
eternal="true">
<cacheEventListenerFactory
class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
properties="replicatePuts=false,replicateUpdatesViaCopy=false" />
</cache>
<cache name="eternalCache" maxElementsInMemory="500"
overflowToDisk="true" eternal="false" timeToIdleSeconds="1200"
timeToLiveSeconds="1200">
<cacheEventListenerFactory
class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
properties="replicatePuts=false,replicateUpdatesViaCopy=false" />
</cache>
<defaultCache maxElementsInMemory="10000" overflowToDisk="true"
eternal="false" memoryStoreEvictionPolicy="LRU" maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="600" timeToIdleSeconds="3600"
timeToLiveSeconds="100000" diskPersistent="false" />
</ehcache>
3.创建CacheManager
CacheManager是Ehcache框架的核心类和入口,它负责管理一个或多个Cache对象。要使用Ehcache框架,必须要先创建CacheManager对象,CacheManager类static类型的创建方法包括:create()、getInstance()
import net.sf.ehcache.CacheManager;
/**
* @Description: Ehcache
* @author Roy_Carroll
* @email yanggang0226@163.com
*/
public class EHCACHE {
public static void main(String[] args) {
CacheManager manager1 = CacheManager.getInstance();
CacheManager manager2 = CacheManager.create();
System.out.println(manager1 == manager2);// true
}
}
4.持久化数据
ehcache可以在程序突然异常中止后,将原来缓存中的数据在程序进行重启的时候重新加载到缓存中去。
- 在web.xml中加入监听
<listener>
<listener-class>net.sf.ehcache.constructs.web.ShutdownListener</listener-class>
</listener>
- 在ehcache.xml文件中修添加配置
<!--overflowToDisk当内存中数据满时写到磁盘,diskPersistent硬盘持久化-->
<cache name="authorCodecache" maxElementsInMemory="1"
overflowToDisk="true" eternal="false" timeToIdleSeconds="0" timeToLiveSeconds="3600"
diskPersistent="true">
</cache>
- 在创建CacheManager对象时setProperty
private static void ehcacheSetUp() {
System.setProperty("net.sf.ehcache.enableShutdownHook", "true"); //持久化使用
manager = CacheManager.create();
}
- 在get方法的时候使用flush()
5.ehcache的简单读写操作
private static Element readSomeData(Cache cache, String key, String value) {
return cache.get(key);
}
private static void writeSomeData(Cache cache, String key, String value) {
cache.put(new Element(key, value));
}
6.txt文档进行读取的简单Demo
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/**
* @Description: Ehcache
* @author Roy_Carroll
* @email yanggang0226@163.com
*/
public class cache {
public static final String AUTHOR_CODE_CACHE = "authorCodecache";
public static Cache authorCodeCache;
public static CacheManager manager ;
public static void main(String[] args) {
File file = new File("C:/Users/Administrator/Desktop/testData.txt");
StringBuilder filetxt = new StringBuilder();
String value = filetxt.append(txt2String(file)).toString();
if (manager==null&&authorCodeCache == null) {
System.setProperty("net.sf.ehcache.enableShutdownHook", "true");
manager = CacheManager.getInstance();
authorCodeCache = manager.getCache(AUTHOR_CODE_CACHE);
ehcacheUse(authorCodeCache,value);
}
}
private static void ehcacheUse(Cache cache,String value) {
cache.getSize();
String key = "20180510";
Element element1 = new Element(key, value);
cache.put(element1);
Element element2 = readSomeData(cache, key, value);
System.out.println(element2);
}
private static Element readSomeData(Cache cache, String key, String value) {
return cache.get(key);
}
public static String txt2String(File file){
StringBuilder result = new StringBuilder();
try{
BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
String s = null;
while((s = br.readLine())!=null){//使用readLine方法,一次读一行
result.append(System.lineSeparator()+s);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
return result.toString();
}
}
- 运行结果(随便找了个我的文档,内容无关紧要可以忽略):
[ key = 20180510, value=
SET GLOBAL general_log = 'ON';
SET GLOBAL slow_query_log = 'ON';
show VARIABLES like '%general_log_file%';
show VARIABLES like '%slow_query_log_file%';
show status like '%lock%';
set global innodb_buffer_pool_size=1610612736
set global query_cache_size=2097152
set global back_log=1500
set global thread_cache_size=50
set global query_cache_size=2097152
set global thread_cache_size=50, version=1, hitCount=1, CreationTime = 1526370703166, LastAccessTime = 1526370703182 ]