关于EHcache缓存

2024-05-30 09:58
文章标签 缓存 ehcache

本文主要是介绍关于EHcache缓存,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 

1、简介

非常简单,而且易用。

    ehcache 是一个非常轻量级的缓存实现,而且从1.2 之后就支持了集群,而且是hibernate 默认的缓存provider。ehcache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。

ehcache可以直接使用。也可以和Hibernate对象/关系框架结合使用。还可以做Servlet缓存。

Cache 存储方式 :内存或磁盘。

官方网站:http://ehcache.sourceforge.net/

主要特征:

1. 快速.

2. 简单.

3. 多种缓存策略

4. 缓存数据有两级:内存和磁盘,因此无需担心容量问题

5. 缓存数据会在虚拟机重启的过程中写入磁盘

6. 可以通过RMI、可插入API等方式进行分布式缓存

7. 具有缓存和缓存管理器的侦听接口

8. 支持多缓存管理器实例,以及一个实例的多个缓存区域

9. 提供Hibernate的缓存实现

10. 等等

二、快速上手

1、  项目类库中添加ehcache.jar;

2、  在类路径下编写ehcache.xml配置文件。

三、配置文件参数详解

ehcache.xml是ehcache的配置文件,并且存放在应用的classpath中。下面是对该XML文件中的一些元素及其属性的相关说明: 

<diskStore>元素:指定一个文件目录,当EHCache把数据写到硬盘上时,将把数据写到这个文件目录下。 下面的参数这样解释:   

         user.home – 用户主目录  

         user.dir     – 用户当前工作目录   

         java.io.tmpdir – 默认临时文件路径

<defaultCache>元素:设定缓存的默认数据过期策略。 

<cache>元素:设定具体的命名缓存的数据过期策略。

<cache>元素的属性 

        name:缓存名称。通常为缓存对象的类名(非严格标准)。 

        maxElementsInMemory:设置基于内存的缓存可存放对象的最大数目。 

        maxElementsOnDisk:设置基于硬盘的缓存可存放对象的最大数目。 

        eternal:如果为true,表示对象永远不会过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false; 

        timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了timeToIdleSeconds属性值,这个对象就会过期。当对象过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地处于空闲状态。 

        timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期。当对象过期,EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义。 

        overflowToDisk:如果为true,表示当基于内存的缓存中的对象数目达到了maxElementsInMemory界限后,会把益出的对象写到基于硬盘的缓存中。注意:如果缓存的对象要写入到硬盘中的话,则该对象必须实现了Serializable接口才行。

memoryStoreEvictionPolicy:缓存对象清除策略。有三种:

        1 FIFO,firstin first out ,这个是大家最熟的,先进先出,不多讲了

        2 LFU , LessFrequently Used ,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存。

        2 LRU ,LeastRecently Used ,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。

 

四、单独使用EHCache

1.创建CacheManager (net.sf.ehcache.CacheManager)

1)使用默认配置文件创建

1

CacheManager manager = CacheManager.create();

(2)使用指定配置文件创建

1

CacheManager manager = CacheManager.create("src/config/ehcache.xml");

(3)从classpath找寻配置文件并创建

1

URL url = getClass().getResource("/anothername.xml");

2

CacheManager manager = CacheManager.create(url);

(4)通过输入流创建

1

InputStream fis = new FileInputStream(new File("src/config/ehcache.xml").getAbsolutePath());

2

try { 

 

3

    manager = CacheManager.create(fis);

4

 } finally { 

 

5

    fis.close(); 

6

}

2.创建Caches (net.sf.ehcache.Cache)

1)取得配置文件中预先定义的sampleCache1设置,生成一个Cache

1

Cache cache = manager.getCache("sampleCache1");

2)设置一个名为test 的新cache,test属性为默认

1

CacheManager manager = CacheManager.create();

2

manager.addCache("test");

3)设置一个名为test 的新cache,并定义其属性

1

CacheManager manager = CacheManager.create();

2

Cache cache = new Cache("test", 1, true, false, 5, 2);

 

3

manager.addCache(cache);

4)删除cache

1

CacheManager singletonManager = CacheManager.create();

2

singletonManager.removeCache("sampleCache1");

3.使用Caches

1)往cache中加入元素

1

Element element = new Element("key1", "value1");

2

cache.put(new Element(element);

2)从cache中取得元素

1

Element element = cache.get("key1");

3)从cache中删除元素

1

Cache cache = manager.getCache("sampleCache1");

2

Element element = new Element("key1", "value1");

 

3

cache.remove("key1");

4.卸载CacheManager ,关闭Cache

1

 manager.shutdown();

下附代码。

五、在 Hibernate 中运用EHCache

1、hibernate.cfg.xml中需设置如下:

3系列版本加入

1

<property name=” hibernate.cache.provider_class”>

2

    org.hibernate.cache.EhCacheProvider

 

3

</property>

EhCacheProvider类位于hibernate3.jar

2.1版本加入

net.sf.ehcache.hibernate.Provider

2.1以下版本加入

net.sf.hibernate.cache.EhCache

 2、在Hibernate3.x中的etc目录下有ehcache.xml的示范文件,将其复制应用程序的src目录下(编译时会把ehcache.xml复制到WEB-INF/classess目录下),对其中的相关值进行更改以和自己的程序相适合。

 3、持久化类的映射文件进行配置

1

<cache usage="read-write"/>

在<set>标记中设置了<cacheusage="read-write"/>,但Hibernate仅把和Group相关的Student的主键id加入到缓存中,如果希望把整个Student的散装属性都加入到二级缓存中,还需要在Student.hbm.xml文件的<class>标记中加入<cache>子标记,如下所示:

1

<cache usage="read-write" /> <!--cache标记需跟在class标记后-->

 注:SSH中hibernate配置的cache信息

1

<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>

 

 

 

 

 

 

 

配置文件demo如下:

<?xml version="1.0"encoding="UTF-8" standalone="yes"?>

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="ehcache.xsd">

    <!--Sets the path to the directory where cache .data files are created.

 

         If the path is a Java System Propertyit is replaced by

         its value in the running VM.

 

         The following properties aretranslated:

         user.home - User's home directory

         user.dir - User's current workingdirectory

         java.io.tmpdir - Default tempfile path -->

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

    <!-- 

    <cacheManagerPeerProviderFactoryclass="net.sf.ehcache.distribution.jgroups.JGroupsCacheManagerPeerProviderFactory"properties="jgroups_tcp.xml"/>

    -->

    <!--DefaultCache configuration. These will applied to caches programmaticallycreated through

        the CacheManager.

 

        The following attributes are required:

 

        maxInMemory                    - Sets the maximum numberof objects that will be created in memory

        eternal                        - Sets whether elementsare eternal. If eternal,  timeouts areignored and the

                                        element is never expired.

        overflowToDisk                 - Sets whether elements canoverflow to disk when the in-memory cache

                                         has reached the maxInMemory limit.

 

        The following attributes are optional:

        timeToIdleSeconds              - Sets the time to idle for anelement before it expires.

                                         i.e.The maximum amount of time between accesses before an element expires

                                         Isonly used if the element is not eternal.

                                        Optional attribute. A value of 0 means that an Element can idle forinfinity.

                                         The defaultvalue is 0.

        timeToLiveSeconds              - Sets the time to live for anelement before it expires.

                                         i.e.The maximum time between creation time and when an element expires.

                                         Isonly used if the element is not eternal.

                                        Optional attribute. A value of 0 means that and Element can live forinfinity.

                                         The default value is 0.

        diskPersistent                 - Whether the disk storepersists between restarts of the Virtual Machine.

                                         Thedefault value is false.

        diskExpiryThreadIntervalSeconds- Thenumber of seconds between runs of the disk expiry thread. The defaultvalue

                                         is 120seconds.

        -->

 

    <defaultCache

       maxElementsInMemory="10000"

       eternal="false"

       timeToIdleSeconds="1800"

        timeToLiveSeconds="1800"

       overflowToDisk="false"       

    />

    <cache name="org.hibernate.cache.StandardQueryCache"

       maxElementsInMemory="10000"

       eternal="false"

       timeToIdleSeconds="1800"

       timeToLiveSeconds="1800"

       overflowToDisk="false"

    />

    <cache name="tinyCacheSet"

       maxElementsInMemory="10000"

       eternal="false"

       timeToIdleSeconds="604800"

       timeToLiveSeconds="1800"

       overflowToDisk="false"

    />  

    <cache name="readOnlyCacheSet"

       maxElementsInMemory="10000"

       eternal="false"

       timeToIdleSeconds="604800"

       timeToLiveSeconds="1800"

       overflowToDisk="false"

    />  

    <cache name="mediumCacheSet"

       maxElementsInMemory="10000"

       eternal="false"

       timeToIdleSeconds="604800"

       timeToLiveSeconds="1800"

       overflowToDisk="false"

    /> 

    <cache name="largeCacheSet"

       maxElementsInMemory="20000"

       eternal="false"

       timeToIdleSeconds="604800"

       timeToLiveSeconds="1800"

       overflowToDisk="false"

    /> 

    <cache name="hugeCacheSet" 

       maxElementsInMemory="50000"

       eternal="false"

       timeToIdleSeconds="604800"

       timeToLiveSeconds="1800"

       overflowToDisk="false"

    />

</ehcache>

这篇关于关于EHcache缓存的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1016099

相关文章

MySQL8.0设置redo缓存大小的实现

《MySQL8.0设置redo缓存大小的实现》本文主要在MySQL8.0.30及之后版本中使用innodb_redo_log_capacity参数在线更改redo缓存文件大小,下面就来介绍一下,具有一... mysql 8.0.30及之后版本可以使用innodb_redo_log_capacity参数来更改

MySQL 缓存机制与架构解析(最新推荐)

《MySQL缓存机制与架构解析(最新推荐)》本文详细介绍了MySQL的缓存机制和整体架构,包括一级缓存(InnoDBBufferPool)和二级缓存(QueryCache),文章还探讨了SQL... 目录一、mysql缓存机制概述二、MySQL整体架构三、SQL查询执行全流程四、MySQL 8.0为何移除查

Redis缓存问题与缓存更新机制详解

《Redis缓存问题与缓存更新机制详解》本文主要介绍了缓存问题及其解决方案,包括缓存穿透、缓存击穿、缓存雪崩等问题的成因以及相应的预防和解决方法,同时,还详细探讨了缓存更新机制,包括不同情况下的缓存更... 目录一、缓存问题1.1 缓存穿透1.1.1 问题来源1.1.2 解决方案1.2 缓存击穿1.2.1

Redis与缓存解读

《Redis与缓存解读》文章介绍了Redis作为缓存层的优势和缺点,并分析了六种缓存更新策略,包括超时剔除、先删缓存再更新数据库、旁路缓存、先更新数据库再删缓存、先更新数据库再更新缓存、读写穿透和异步... 目录缓存缓存优缺点缓存更新策略超时剔除先删缓存再更新数据库旁路缓存(先更新数据库,再删缓存)先更新数

el-select下拉选择缓存的实现

《el-select下拉选择缓存的实现》本文主要介绍了在使用el-select实现下拉选择缓存时遇到的问题及解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录项目场景:问题描述解决方案:项目场景:从左侧列表中选取字段填入右侧下拉多选框,用户可以对右侧

SpringBoot使用注解集成Redis缓存的示例代码

《SpringBoot使用注解集成Redis缓存的示例代码》:本文主要介绍在SpringBoot中使用注解集成Redis缓存的步骤,包括添加依赖、创建相关配置类、需要缓存数据的类(Tes... 目录一、创建 Caching 配置类二、创建需要缓存数据的类三、测试方法Spring Boot 熟悉后,集成一个外

使用Spring Cache时设置缓存键的注意事项详解

《使用SpringCache时设置缓存键的注意事项详解》在现代的Web应用中,缓存是提高系统性能和响应速度的重要手段之一,Spring框架提供了强大的缓存支持,通过​​@Cacheable​​、​​... 目录引言1. 缓存键的基本概念2. 默认缓存键生成器3. 自定义缓存键3.1 使用​​@Cacheab

Nacos客户端本地缓存和故障转移方式

《Nacos客户端本地缓存和故障转移方式》Nacos客户端在从Server获得服务时,若出现故障,会通过ServiceInfoHolder和FailoverReactor进行故障转移,ServiceI... 目录1. ServiceInfoHolder本地缓存目录2. FailoverReactorinit

缓存雪崩问题

缓存雪崩是缓存中大量key失效后当高并发到来时导致大量请求到数据库,瞬间耗尽数据库资源,导致数据库无法使用。 解决方案: 1、使用锁进行控制 2、对同一类型信息的key设置不同的过期时间 3、缓存预热 1. 什么是缓存雪崩 缓存雪崩是指在短时间内,大量缓存数据同时失效,导致所有请求直接涌向数据库,瞬间增加数据库的负载压力,可能导致数据库性能下降甚至崩溃。这种情况往往发生在缓存中大量 k

Redis中使用布隆过滤器解决缓存穿透问题

一、缓存穿透(失效)问题 缓存穿透是指查询一个一定不存在的数据,由于缓存中没有命中,会去数据库中查询,而数据库中也没有该数据,并且每次查询都不会命中缓存,从而每次请求都直接打到了数据库上,这会给数据库带来巨大压力。 二、布隆过滤器原理 布隆过滤器(Bloom Filter)是一种空间效率很高的随机数据结构,它利用多个不同的哈希函数将一个元素映射到一个位数组中的多个位置,并将这些位置的值置