一看就会系列之ehcache入门

本文介绍了Ehcache的基础知识,包括它的特性,并通过四个步骤展示了如何配置、实现和测试Ehcache缓存系统。在配置文件中,重点关注了timeToIdleSeconds和timeToLiveSeconds参数,分别控制缓存闲置和存活时间。在测试中,验证了这两个参数的实际效果,证实了Ehcache的缓存管理和销毁机制。
摘要由CSDN通过智能技术生成

百度解释:Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。

一、依赖包

pom.xml

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

二、配置文件

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <!--timeToIdleSeconds 当缓存闲置n秒后销毁 -->
    <!--timeToLiveSeconds 当缓存存活n秒后销毁 -->
    <!--
    缓存配置
    name:缓存名称。
    maxElementsInMemory:缓存最大个数。
    eternal:对象是否永久有效,一但设置了,timeout将不起作用。
    timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
    timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
    overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
    diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
    maxElementsOnDisk:硬盘最大缓存个数。
    diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
    diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
    memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
    clearOnFlush:内存数量最大时是否清除。
    -->

<!-- 指定一个文件目录,当EhCache把数据写到硬盘上时,将把数据写到这个文件目录下 -->
    <diskStore path="C:/Users/infi/Desktop"/>

    <!-- 设定缓存的默认数据过期策略 -->
    <defaultCache
            maxElementsInMemory="10000" 
            eternal="false" 
            overflowToDisk="true"
            timeToIdleSeconds="10"
            timeToLiveSeconds="20"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"/>

    <cache name="cacheTest"
        maxElementsInMemory="1000"
        eternal="false"
        overflowToDisk="true"
        timeToIdleSeconds="10"
        timeToLiveSeconds="20"/>
        
</ehcache>
    
    

注意:timeToIdleSeconds 和 timeToLiveSeconds,这两个参数设置的是10和20,等下针对它们进行测试。

 

applicationContext.xml,里面引入了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"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">


	<context:component-scan base-package="com.zhuyun"/>
  
    <cache:annotation-driven cache-manager="cacheManager" />  

    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">  
        <property name="cacheManager" ref="ehcache"></property>  
    </bean>  

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

三、实现代码

EhCacheTestService.java

package com.zhuyun.ehcache;

public interface EhCacheTestService {
	 public String getTimestamp(String param);
}

该接口很简单,根据一个参数,获取返回值。下面是实现类:

 

EhCacheTestServiceImpl.java

package com.zhuyun.ehcache;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service("ehCacheTestService")
public class EhCacheTestServiceImpl implements EhCacheTestService {
	
	 @Cacheable(value="cacheTest",key="#param")
	 public String getTimestamp(String param) {
        Long timestamp = System.currentTimeMillis();
        return timestamp.toString();
    }
}

该类需要使用@Cacheable注释,value的值cacheTest即是ehcache.xml配置文件中设置的缓存策略。

 

四、测试类

EhCacheTestServiceTest.java

package com.zhuyun.ehcache;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class EhCacheTestServiceTest{
	
	public static void main(String[] args) {
	 try {
			 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
			 EhCacheTestService	ehCacheTestService = (EhCacheTestService) context.getBean("ehCacheTestService");
			 
			 //测试当缓存闲置10秒后销毁
		     System.out.println("第一次调用:" + ehCacheTestService.getTimestamp("param"));
		     Thread.sleep(2000);
		     System.out.println("2秒之后调用:" + ehCacheTestService.getTimestamp("param"));
		     Thread.sleep(11000);
		     System.out.println("再过11秒之后调用:" + ehCacheTestService.getTimestamp("param"));
		     System.out.println();
		     
		     //当缓存存活20秒后销毁
		     System.out.println("第一次调用另一个参数:" + ehCacheTestService.getTimestamp("param2"));
		     Thread.sleep(5000);
		     System.out.println("5秒后调用一次:" + ehCacheTestService.getTimestamp("param2"));
		     Thread.sleep(5000);
		     System.out.println("10秒后调用一次:" + ehCacheTestService.getTimestamp("param2"));
		     Thread.sleep(5000);
		     System.out.println("15秒后调用一次:" + ehCacheTestService.getTimestamp("param2"));
		     Thread.sleep(6000);
		     System.out.println("21秒后调用一次:" + ehCacheTestService.getTimestamp("param2"));
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

测试结果如下:

 

从ehcache.xml文件中,我们设置了timeToIdleSeconds="10",意思是当缓存闲置10秒后销毁 。上图中可以看出,在10秒内我们使用相同的参数调用时,返回的结果是相同的,所以结果是从缓存中直接拿出来的。

另外,我们也设置了timeToLiveSeconds="20",意思是当缓存存活20秒后销毁,即使缓存一直被使用,过了20秒一样会被销毁。从上图中也可以看出,虽然我们每过5秒调用一次,20秒之后,缓存依然不存在了。

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
本实例的环境 eclipse + maven + spring + ehcache + junit EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。Ehcache是一种广泛使用的开 源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。 优点: 1. 快速 2. 简单 3. 多种缓存策略 4. 缓存数据有两级:内存和磁盘,因此无需担心容量问题 5. 缓存数据在虚拟机重启的过程中写入磁盘 6. 可以通过RMI、可插入API等方式进行分布式缓存 7. 具有缓存和缓存管理器的侦听接口 8. 支持多缓存管理器实例,以及一个实例的多个缓存区域 9. 提供Hibernate的缓存实现 缺点: 1. 使用磁盘Cache的时候非常占用磁盘空间:这是因为DiskCache的算法简单,该算法简单也导致Cache的效率非常高。它只是对元素直接追加存储。因此搜索元素的时候非常的快。如果使用DiskCache的,在很频繁的应用中,很快磁盘满。 2. 不能保证数据的安全:当突然kill掉java的时候,可能产生冲突,EhCache的解决方法是如果文件冲突了,则重建cache。这对于Cache 数据需要保存的时候可能不利。当然,Cache只是简单的加速,而不能保证数据的安全。如果想保证数据的存储安全,可以使用Bekeley DB Java Edition版本。这是个嵌入式数据库。可以确保存储安全和空间的利用率。 EhCache的分布式缓存有传统的RMI,1.5版的JGroups,1.6版的JMS。分布式缓存主要解决集群环境中不同的服务器间的数据的同步问题。 使用Spring的AOP进行整合,可以灵活的对方法的返回结果对象进行缓存
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值