EhCache在JAVA中的应用

先看看Ehcache:(这段话是copy的)

 Ehcachejava项目广泛的使用。它是一个开源的、设计于提高在数据从RDBMS中取出来的高花费、高延迟采取的一种缓存方案。正因为Ehcache具有健壮性(基于java开发)、被认证(具有apache 2.0  license)、充满特色(稍后会详细介绍),所以被用于大型复杂分布式web application的各个节点中。

什么特色?

1.  够快

Ehcache的发行有一段时长了,经过几年的努力和不计其数的性能测试,Ehcache终被设计于large, high concurrency systems.

2. 够简单

开发者提供的接口非常简单明了,从Ehcache的搭建到运用运行仅仅需要的是你宝贵的几分钟。其实很多开发者都不知道自己用在用EhcacheEhcache被广泛的运用于其他的开源项目,比如:hibernate

3.够袖珍

关于这点的特性,官方给了一个很可爱的名字small foot print ,一般Ehcache的发布版本不会到2MV2.2.3   668KB

4. 够轻量

核心程序仅仅依赖slf4j这一个包,没有之一!

5.好扩展

Ehcache提供了对大数据的内存和硬盘的存储,最近版本允许多实例、保存对象高灵活性、提供LRULFUFIFO淘汰算法,基础属性支持热配置、支持的插件多

6.监听器

缓存管理器监听器 (CacheManagerListener)和 缓存监听器(CacheEvenListener,做一些统计或数据一致性广播挺好用的。


废话不说了。直接看看怎么个用法吧:

使用ehcache之前需要把  ehcache-2.8.3.jar和 slf4j-api-1.7.7.jar 导入工程中 (jar包网上很多,自己下载就好了。版本不一定相同,我这里只是目前在用的版本)。


首先要创建ehcache的配置文件:


<?xml version="1.0" encoding="UTF-8"?>  
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">  

<diskStore path="java.io.tmpdir/ehcache"/>  

<!-- service 缓存配置 -->
<!-- 注意:name是使用的时候要获取ehcache的实例名称 -->
<cache name="serviceCache"
	eternal="true"  
    maxElementsInMemory="2000" 
    maxElementsOnDisk="5000"
    overflowToDisk="true" 
    diskPersistent="false"
    timeToIdleSeconds="3000" 
    timeToLiveSeconds="3000"  
    memoryStoreEvictionPolicy="LRU" /> 
</ehcache> 



<!-- 
参数说明:

<diskStore>:当内存缓存中对象数量超过maxElementsInMemory时,将缓存对象写到磁盘缓存中(需对象实现序列化接口)。

<diskStore path="">:用来配置磁盘缓存使用的物理路径,Ehcache磁盘缓存使用的文件后缀名是*.data和*.index。

name:缓存名称,cache的唯一标识(ehcache会把这个cache放到HashMap里)。

maxElementsOnDisk:磁盘缓存中最多可以存放的元素数量,0表示无穷大。

maxElementsInMemory:内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况。

1)若overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中。

2)若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素。

Eternal:缓存中对象是否永久有效,即是否永驻内存,true时将忽略timeToIdleSeconds和timeToLiveSeconds。

timeToIdleSeconds:缓存数据在失效前的允许闲置时间(单位:秒),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,此为可选属性即访问这个cache中元素的最大间隔时间,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除。

timeToLiveSeconds:缓存数据在失效前的允许存活时间(单位:秒),仅当eternal=false时使用,默认值是0表示可存活时间无穷大,即Cache中的某元素从创建到清楚的生存时间,也就是说从创建开始计时,当超过这个时间时,此元素将从Cache中清除。

overflowToDisk:内存不足时,是否启用磁盘缓存(即内存中对象数量达到maxElementsInMemory时,Ehcache会将对象写到磁盘中),会根据标签中path值查找对应的属性值,写入磁盘的文件会放在path文件夹下,文件的名称是cache的名称,后缀名是data。

diskPersistent:是否持久化磁盘缓存,当这个属性的值为true时,系统在初始化时会在磁盘中查找文件名为cache名称,后缀名为index的文件,这个文件中存放了已经持久化在磁盘中的cache的index,找到后会把cache加载到内存,要想把cache真正持久化到磁盘,写程序时注意执行net.sf.ehcache.Cache.put(Element element)后要调用flush()方法。

diskExpiryThreadIntervalSeconds:磁盘缓存的清理线程运行间隔,默认是120秒。

diskSpoolBufferSizeMB:设置DiskStore(磁盘缓存)的缓存区大小,默认是30MB

memoryStoreEvictionPolicy:内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存,共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)。


 -->



然后在spring配置文件中配置:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
	 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd  
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 
     http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd 
     http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">


	<bean id="SpringContextUtil" class="com.im.utils.SpringContextUtil"
		scope="singleton"></bean>

	<!-- 配置支持chcache缓存 -->
	<cache:annotation-driven cache-manager="ehcacheCacheManager" />
	<bean id="ehcacheCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
		<property name="cacheManager" ref="ehcacheManager" />
	</bean>

	<bean id="ehcacheManager"
		class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
		<property name="configLocation" value="classpath:ehcache/ehcache.xml" />
	</bean>

	<!-- 导入quartz配置的文件 -->
	<import resource="spring-quartz.xml" />

	<!-- 导入dubbo配置的文件 -->
	<import resource="../dubbo/dubbo-user.xml" />

	<!-- 导入redis配置文件 -->
	<import resource="spring-redis.xml" />


</beans>

配置非常简单,到这里基本可以正常使用EHCache了。下面给一个工具类方便使用:


package com.im.socket.utils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * EHCache使用工具类
 * 
 * @author kokJuis
 */
public class EHCacheUtil {

    private static EHCacheUtil ehCacheUtil;

    private CacheManager cacheManager;

    private Cache cache;

    private EHCacheUtil() {
        cacheManager = CacheManager.create();
        this.cache = cacheManager.getCache("serviceCache");//这个名称就是配置文件里面对应的name
    }

    //单例模式
    public static EHCacheUtil getEHCacheUtil() {

        if (ehCacheUtil == null) {
            ehCacheUtil = new EHCacheUtil();
        }
        return ehCacheUtil;
    }

    public Cache getCache() {
        return cache;
    }

    public void setCache(Cache cache) {
        this.cache = cache;
    }

    /*
     * 通过名称从缓存中获取数据
     */
    public Object getCacheElement(String cacheKey) throws Exception {
        Element e = cache.get(cacheKey);
        if (e == null) {
            return null;
        }
        return e.getObjectValue();
    }

    /*
     * 将对象添加到缓存中
     */
    public void addToCache(String cacheKey, Object result) throws Exception {
        Element element = new Element(cacheKey, result);
        cache.put(element);
    }

    /**
     * 将对象从缓存中删除
     * 
     * @param cacheKey
     * @return
     * @author kokJuis
     * @date 2016-4-28 下午3:06:00
     * @comment
     */
    public boolean removeToCache(String cacheKey) throws Exception {
        return cache.remove(cacheKey);
    }

    /**
     * 获取给定Key的Write锁
     * 
     * @author kokJuis
     * @version 1.0
     * @date 2016-12-7
     * @param cacheKey
     */
    public void acquireWriteLockOnKey(String cacheKey) {
        cache.acquireWriteLockOnKey(cacheKey);
    }

    /**
     * 获取给定Key的Read锁
     * 
     * @author kokJuis
     * @version 1.0
     * @date 2016-12-7
     * @param cacheKey
     */
    public void acquireReadLockOnKey(String cacheKey) {
        cache.acquireReadLockOnKey(cacheKey);
    }

    /**
     * 释放所持有的给定Key的Read锁
     * 
     * @param key
     */
    public void releaseReadLockOnKey(String key) {
        cache.releaseReadLockOnKey(key);
    }

    /**
     * 释放所持有的给定Key的Write锁
     * 
     * @param key
     */
    public void releaseWriteLockOnKey(String key) {
        cache.releaseWriteLockOnKey(key);
    }

}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值