缓存:
使用JSP标签缓存部分页面(cache,usecached,flush,addgroup,addgroups)
使用过滤器缓存整个页面(CacheFilter)
使用OSCache API缓存JAVA对象(GeneralCacheAdministrator)
Hibernate中使用OSCache
EHcache 数据库缓存
Memcache 分布式
场景:将常用数据放置在缓存中,降低访问数据库的频率,提高响应速度
ehcache
非常简单,而且易用。
ehcache 是一个非常轻量级的缓存实现,而且从1.2 之后就支持了集群,而且是hibernate 默认的缓存provider。ehcache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
ehcache可以直接使用。也可以和Hibernate对象/关系框架结合使用。还可以做Servlet缓存。
Cache 存储方式 :内存或磁盘。
ehcache.xml
--自定义
--default有什么作用?--方便在代码中用new Cache(xx,xx,xx,xx,xx)生成缓存对象
关于元素的过期时间
a) timeToIdleSeconds(空闲时间)、timeToLiveSeconds(生存时间)都设置为0时,表示不过期
b) 如果只有timeToLiveSeconds设置>0的值,则Element的过期时间为 timeToLiveSeconds
c) 如果只有timeToIdleSeconds设置>0的值,则Element的过期时间为 (上次访问时间+timeToIdleSeconds),说得更通俗点,上次get过了,现在又想get,若二次get的时间间隔>timeToIdleSeconds,则过期(即:最后一次get出来为null)
d) 如果timeToLiveSeconds、timeToIdleSeconds都有>0的值,则最终过期时间为 b),c)规则综合起来,取二者的最小值
参数设置建议:
a) 如果缓存的数据本身不存在更新(比如:一些几乎从来不动的基础数据),只设置timeToIdleSeconds,这样的好处是,如果缓存项一直有人在访问,就永远不会过期,反之,如果没人用,空闲一段时间后,会自动过期,释放资源
b) 如果缓存的数据本身存在定期的更新问题(比如:天气预报之类每隔几小时,db中会更新的数据),可同时设置二个参数,timeToLiveSeconds的值应该要小于db中的更新周期,这样db中的数据变化后,过一段时间就会更新到缓存中
========================================>java-maven
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- log begin -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.6</version>
</dependency>
ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"> <diskStore path="java.io.tmpdir" /> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap" /> </defaultCache> <cache name="sampleCache1" maxEntriesLocalHeap="10000" maxEntriesLocalDisk="1000" eternal="false" diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" transactionalMode="off"> <persistence strategy="localTempSwap" /> </cache> <cache name="sampleCache2" maxEntriesLocalHeap="1000" eternal="true" memoryStoreEvictionPolicy="FIFO" /> </ehcache>
代码
import java.util.Arrays; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; /** * Hello world! * */ public class App { public static void main(String[] args) { CacheManager manager = CacheManager.create(); String[] names = manager.getCacheNames(); System.out.println("=================所有的缓存对象================="); System.out.println(Arrays.toString(names)); System.out.println("------------------------------------------------"); // 得到一个cache对象 Cache cache1 = manager.getCache(names[0]); // 向cache1对象里添加缓存 cache1.put(new Element("key1", "values1")); Element element = cache1.get("key1"); System.out.println("key1所对应的值为: " + element.getObjectValue()); System.out.println("------------------------------------------------"); // 手动创建一个cache Cache cache2 = new Cache("cacheByCode", 1, true, false,2, 0); System.out.println(cache2); manager.addCache(cache2); cache2.put(new Element("key2", "value2")); Element e = cache2.get("key2"); System.out.println(e.getExpirationTime()); System.out.println(e.getCreationTime()); manager.shutdown(); } }
========================================>
java-spring-maven
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<!-- 指定一个文件目录,当EhCache把数据写到硬盘上时,将把数据写到这个文件目录下 -->
<diskStore path="java.io.tmpdir"/>
<!-- 设定缓存的默认数据过期策略 -->
<!--
参数说明:
name:缓存名称
maxElementsInMemory:内存中最大的缓存对象数
eternal:true表示对象永不过期
overflowToDisk:true表示当内存缓存的对象数达到maxElementsInMemory后,会把溢出的对象写到硬盘缓存中。(ps:如果需要写到磁盘中,则写入的对象必须实现Serializable接口)
timeToIdleSeconds:设定允许对象处于空闲状态的最长时间,以秒为单位。(ps:这个属性只有当eternal属性为false才有效)
timeToLiveSeconds:设定对象允许存在于缓存中的最大生存时间,以秒为单位。(ps:这个属性只有当eternal属性为false才有效)
diskPersistent:是否缓存虚拟机重启期数据,是否持久化磁盘缓存,当这个属性的值为true时,系统在初始化时会在磁盘中查找文件名为cache名称,
后缀名为index的文件,这个文件中存放了已经持久化在磁盘中的cache的index,找到后会把cache加载到内存,要想把cache真正持久化到磁盘,写程
序时注意执行net.sf.ehcache.Cache.put(Element element)后要调用flush()方法。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认为120秒
-->
<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>
<properties>
<!-- 项目编码 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- junit版本号 -->
<junit.version>4.12</junit.version>
<!-- spring版本号 -->
<spring.version>3.2.8.RELEASE</spring.version>
</properties>
<dependencies>
<!-- 添加单元测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<!-- 添加Spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring单元测试依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- ehcache 相关依赖 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>
serviceImpl:
import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class EhcacheServiceImpl implements EhcacheService { @Cacheable(value = "cacheTest", key = "#param") public String getTime(String param) { return String.valueOf(System.currentTimeMillis()); } }
JunitTest:
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration(locations = { "classpath:applicationContext.xml" }) @RunWith(SpringJUnit4ClassRunner.class) public class EhcacheTest extends AbstractJUnit4SpringContextTests { @Autowired private EhcacheService ehcacheService; @Test public void testEhcache() throws InterruptedException { System.out.println("第一次调用:" + ehcacheService.getTime("param")); Thread.sleep(2000); System.out.println("第二次调用(2秒后):" + ehcacheService.getTime("param")); Thread.sleep(10000); System.out.println("第三次调用(10秒后):" + ehcacheService.getTime("param")); } }
浙公网安备 33010602011771号