缓存框架Ehcacahe的学习与使用(二):Ehcache入门使用

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

    CacheManagerEhcache框架的核心类和入口,它负责管理一个或多个Cache对象。要使用Ehcache框架,必须要先创建CacheManager对象,CacheManagerstatic类型的创建方法包括: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()
    因为ehcache 持久化数据是根据 .index 索引文件进行数据恢复,从而达到数据持久化的目的,但程序启动以后无法加载之前缓存中的数据,所以应在使用 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 ]


                
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值