Ehcache 缓存

简介

Ehcache在很多项目中都出现过,用法也比较简单。一般的加些配置就可以了,而且Ehcache可以对页面、对象、数据进行缓存,同时支持集群/分布式缓存。如果整合Spring、Hibernate也非常的简单,Spring对Ehcache的支持也非常好。EHCache支持内存和磁盘的缓存,支持LRU、LFU和FIFO多种淘汰算法,支持分布式的Cache,可以作为Hibernate的缓存插件。同时它也能提供基于Filter的Cache,该Filter可以缓存响应的内容并采用Gzip压缩提高响应速度。

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.lee</groupId>
    <artifactId>ehcache</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>ehcache Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <version>2.5.2</version>
        </dependency>
        <!--主要针对页面缓存 <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-web</artifactId> <version>2.0.4</version> </dependency> -->
    </dependencies>
    <build>
        <finalName>ehcache</finalName>
    </build>
</project>

ehcache.xml配置文件

<?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="D:\\Develop\\cache"/>  

    <!-- Mandatory Default Cache configuration. These settings will be applied to caches created programmtically using CacheManager.add(String cacheName) -->  
    <!-- name:缓存名称。 maxElementsInMemory:缓存最大个数。 eternal:对象是否永久有效,一但设置了,timeout将不起作用。 timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。 仅当eternal=false对象不是永久有效时使用, 可选属性,默认值是0,也就是可闲置时间无穷大。 timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。 最大时间介于创建时间和失效时间之间。 仅当eternal=false对象不是永久有效时使用, 默认是0.,也就是对象存活时间无穷大。 overflowToDisk:当内存中对象数量达到maxElementsInMemory时, Ehcache将会对象写到磁盘中。 diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。 默认是30MB。 每个Cache都应该有自己的一个缓冲区。 maxElementsOnDisk:硬盘最大缓存个数。 diskPersistent:是否缓存虚拟机重启期数据 diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。 memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时, Ehcache将会根据指定的策略去清理内存。 默认策略是LRU(最近最少使用)。 你可以设置为FIFO(先进先出)或是LFU(较少使用)。 clearOnFlush:内存数量最大时是否清除。 -->  
    <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />  

    <cache name="demo" maxElementsInMemory="10" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" maxElementsOnDisk="100" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />

    <cache name="SimplePageCachingFilter" maxElementsInMemory="10000" eternal="false" overflowToDisk="false" timeToIdleSeconds="900" timeToLiveSeconds="1800" memoryStoreEvictionPolicy="LFU" />
</ehcache>  

Ehcache API

package com.lee.ehcache;

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

public class Api {
    public static void main(String[] args) {
        /* * 多种创建CacheManager方法: cacheManager = CacheManager.getInstance(); * cacheManager = CacheManager.newInstance("/ehcache.xml"); * cacheManager = CacheManager.create(); */
        CacheManager cacheManager = CacheManager.create();

        // 获取ehcache配置文件中的一个cache
        Cache demo = cacheManager.getCache("demo");

        // 添加数据到缓存中
        Element element = new Element("key", "val");
        demo.put(element);

        // 获取缓存中的对象,注意添加到cache中对象要序列化 实现Serializable接口
        //Element result = demo.get("key");

        // 获取缓存管理器中的缓存配置名称
        for (String cacheName : cacheManager.getCacheNames()) {
            System.out.println(cacheName);
        }

        // 获取所有的缓存对象
        for (Object key : demo.getKeys()) {
            System.out.println(key);
        }

        // 得到缓存中的对象数
        System.out.println(demo.getSize());
        // 得到缓存对象占用内存的大小
        System.out.println(demo.getMemoryStoreSize());
        // 得到缓存读取的命中次数
        System.out.println(demo.getStatistics().getCacheHits());
        // 得到缓存读取的错失次数
        System.out.println(demo.getStatistics().getCacheMisses());

        // 删除缓存
        demo.remove("key");
        demo.removeAll();
    }
}

Hibernate启动二级缓存

EhCache是Hibernate的二级缓存技术之一,可以把查询出来的数据存储在内存或者磁盘,节省下次同样查询语句再次查询数据库,大幅减轻数据库压力;
当用Hibernate的方式修改表数据(save,update,delete等等),这时EhCache会自动把缓存中关于此表的所有缓存全部删除掉(这样能达到同步)。但对于数据经常修改的表来说,可能就失去缓存的意义了(不能减轻数据库压力);
在比较少更新表数据的情况下,EhCache一般要使用在比较少执行write操作的表(包括update,insert,delete等)[Hibernate的二级缓存也都是这样];对并发要求不是很严格的情况下,两台机子中的缓存是不能实时同步的;

hibernate.cfg.xml

<!-- Hibernate 3.3+ -->  
<!-- <property name="hibernate.cache.region.factory_class"> net.sf.ehcache.hibernate.EhCacheRegionFactory </property> <property name="hibernate.cache.region.factory_class"> net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory </property> -->  
<!-- hibernate3.0-3.2 cache config-->  
<!-- <property name="hibernate.cache.region.factory_class"> net.sf.ehcache.hibernate.EhCacheProvider </property> -->  
<property name="hibernate.cache.provider_class">
    net.sf.ehcache.hibernate.SingletonEhCacheProvider
</property>  

<!-- Enable Second-Level Cache and Query Cache Settings -->  
<property name="hibernate.cache.use_second_level_cache">true</property>  
<property name="hibernate.cache.use_query_cache">true</property>

<!-- ehcache不支持transactional,其他三种可以支持。 read- only:无需修改, 可以对其进行只读缓存, 注意:在此策略下,如果直接修改数据库,即使能够看到前台显示效果, 但是将对象修改至cache中会报error,cache不会发生作用。 另:删除记录会报错,因为不能在read-only模式的对象从cache中删除。 read-write:需要更新数据,那么使用读/写缓存比较合适, 前提:数据库不可以为serializable transaction isolation level(序列化事务隔离级别) nonstrict-read-write:只偶尔需要更新数据(也就是说,两个事务同时更新同一记录的情况很不常见), 也不需要十分严格的事务隔离,那么比较适合使用非严格读/写缓存策略。 -->  
<class-cache class="com.hoo.hibernate.entity.User" usage="read-write" />

你可能感兴趣的:(Hibernate,ehcache,缓存,二级缓存)