`
从百草园到三味书屋
  • 浏览: 51975 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

hibernate二级缓存之ehcache初探

    博客分类:
  • WEB
阅读更多
一、Ehcache简介
      EhCache是Hibernate的二级缓存技术之一,可以把查询出来的数据存储在内存或者磁盘,节省下次同样查询语句再次查询数据库,大幅减轻数据库压力;
      当用Hibernate对关系型数据库表进行更改时(DELETE/UPDATE),这时EhCache会自动把缓存中关于此表的所有缓存全部删除掉,以此来达到同步效果。基于这一点来说,ehcache不适合那种经常修改数据库表的情形。
      Ehcache适用场合:
  • 1)对数据库表很少修改;
  • 2)对并发要求不是很严格。

      对于工业传感器实时数据,程序对其保存后,利用二级缓存技术查看历史数据。我本人也是基于这种场景才用ehcache的
二、准备工作
[list]
  • ehcache-core.jar ehcache核心包,在maven项目中,类似于如下引入
  • <dependency>
    	<groupId>net.sf.ehcache</groupId>
    	<artifactId>ehcache-core</artifactId>
    	<version>2.4.3</version>
    </dependency>
    
  • ehcache-spring-annotations 基于spring注解ehcache,在maven项目中,类似于如下引入
  • <groupId>com.googlecode.ehcache-spring-annotations</groupId>
    	<artifactId>ehcache-spring-annotations</artifactId>
    	<version>1.1.2</version>
    	<type>jar</type>
    	<scope>compile</scope>
    </dependency>
    
  • 其他jar包(例如hibernate系列、spring web系列,commons系列)
  • [/list]
    三、Ehcache.xml配置
          Ehcache.xml文件时ehcache二级缓存最主要的我配置文件,它定义了对哪些实体对象进行缓存,以及缓存策略,直接上一个配置片段把
    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache>
    	<cache name="entity.HistoryData"
    	       maxElementsInMemory="5000" eternal="false" timeToIdleSeconds="300"
    	       timeToLiveSeconds="7200" overflowToDisk="false" />
    </ehcache>


    name要缓存的实体类的名称
    maxElementsInMemory设置该缓存实体的最大个数
    eternal对象是否永久有效
    timeToIdleSeconds设置对象在失效前的允许闲置时间(单位:s)
    timeToLiveSeconds设置对象在失效前允许存活时间(单位:s)
    overflowToDisk当缓存中对象达到maxElementsInMemory时,存入磁盘
    diskSpoolBufferSizeMB设置磁盘缓冲区大小
    maxElementsOnDisk设置磁盘能缓存最大对象个数
    diskPersistent是否缓存虚拟机重启期数
    diskExpiryThreadIntervalSeconds磁盘失效线程运行时间间隔,默认是120秒。
    memoryStoreEvictionPolicy当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。 
    clearOnFlush内存数量最大时是否清除。

    两个问题:
    • 该文件放置在那里?该文件可以放置在工程的任意位置
    • 该文件如何引入?或者说ehcache.xml路径是如何确定的?

        我们可以通过查阅相关源码,可知
    在hibernate.cache.provider所指定的类net.sf.ehcache.hibernate.EhCacheRegionFactory类的抽象类AbstractEhcacheRegionFactory中,对NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME中有明确的解释:
    /**
    The Hibernate system property specifying the location of the ehcache configuration file name.
        If not set, ehcache.xml will be looked for in the root of the classpath.
    If set to say ehcache-1.xml, ehcache-1.xml will be looked for in the root of the classpath.
    **/
    

    [/list]
    四、集成到spring
          这一个步骤分为两部分,一部分是对ehcache打开注解功能,另一部分是集成hibernate sesionFactory中
    [list]
  • 配置注解,新建spring-ehcache.xml,并在web.xml param中引入,如下:
    <?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:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
    	xsi:schemaLocation="  
        	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
        	http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">
    	<ehcache:annotation-driven />
    	<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    		<property name="configLocation" value="classpath:ehcache.xml" />
    	</bean>
    	<ehcache:config cache-manager="cacheManager"/>
    </beans>

    注:对于命名空间,前提是引入ehcache-spring-annotations.jar包,否则提示无法解析该命名空间。ConfigLocation指定ehcache.xml配置文件所在的路径。
  • hibernate sessionFactory配置,新建spring-sessionFactory.xml,并在web.xml中引入,如下
  • <?xml version="1.0" encoding="utf-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xmlns:util="http://www.springframework.org/schema/util" xmlns:jee="http://www.springframework.org/schema/jee"
    	xmlns:lang="http://www.springframework.org/schema/lang" xmlns:jms="http://www.springframework.org/schema/jms"
    	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                               http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
                               http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
                               http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
                               http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd
                               http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                               http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                               http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
      
       <context:property-placeholder location="classpath:/resource.properties" />
       
       <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
       		<property name="driverClass" value="${jdbc.driverClassName}"/>
       		<property name="jdbcUrl" value="${jdbc.url}"/>
       		<property name="user" value="${jdbc.username}"/>
       		<property name="password" value="${jdbc.password}"/>
       		<property name="idleConnectionTestPeriod" value="120"/>
      	</bean>
      	<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
      		<property name="dataSource" ref="dataSource"/>
      		<property name="schemaUpdate" value="${hibernate.schemaUpdate}"/>
      		<property name="packagesToScan" value="${hibernate.packageScan}"/>
    		<property name="hibernateProperties">
    			<value>
    				hibernate.dialect ${hibernate.dialect}
    				hibernate.show_sql ${hibernate.show_sql}
    				hibernate.cache.region.factory_class ${hibernate.cache.provider}
                    hibernate.cache.use_second_level_cache ${hiberante.second.cache}
    		[color=red]Hibernate.cache.use_query_cache true	[/color]	
    			</value>
    		</property>
    	</bean>
    </beans>

    其中,
    • hibernate.cache.provider 选择二级缓存实现的类
    • Hibernate.cache.use_second_level_cache:选择是否开启二级缓存
    • Hibernate.cache.use_query_cache 是否开启查询缓存(重要,后面讲到)

    [/list]
    五、测试
    新建一个实体类
    package entity;
    
    import java.io.Serializable;
    import java.util.Date;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    import org.hibernate.annotations.Cache;
    import org.hibernate.annotations.CacheConcurrencyStrategy;
    
    @Entity
    @Table(name="history_data")
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    public class HistoryData implements Serializable{
    	//省略
    }

    把这个类映射到数据库表中。并且设置缓存方式

    缓存方式有四种
    参考资料 写道
    CacheConcurrencyStrategy.NONE
       CacheConcurrencyStrategy.READ_ONLY ,只读模式,在此模式下,如果对数据进行更新操作,会有异常;
       CacheConcurrencyStrategy.READ_WRITE ,读写模式在更新缓存的时候会把缓存里面的数据换成一个锁,其它事务如果去取相应的缓存数据,发现被锁了,直接就去数据库查询;
       CacheConcurrencyStrategy.NONSTRICT_READ_WRITE ,不严格的读写模式则不会的缓存数据加锁;
       CacheConcurrencyStrategy.TRANSACTIONAL ,事务模式指缓存支持事务,当事务回滚时,缓存也能回滚,只支持 JTA 环境。

    缓存的注释写法如下,加在 Entity 的 java 类上:
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)

        如果我们要对hql查询设置缓存,可以通过设置this.getHibernateTemplate().setCacheQueries(boolean)来实现,前提是开启查询缓存。下面是一个例子:
    public List<HistoryData> list(String name,String location,Date startTime,
    			Date endTime, boolean alarm,int start,int limit){
    		String hql = "from HistoryData hd where 1=1 ";
    		if(StringUtils.isNotBlank(name)){
    			hql+= " and hd.name like '%"+name+"%' ";
    		}
    		if(StringUtils.isNotBlank(location)){
    			hql+= " and hd.location like '"+location+"' ";
    		}
    		this.getHibernateTemplate().setCacheQueries(true);
    		List<HistoryData> hds =  this.findByNamedParam(hql, null, null, start, limit);
    		this.getHibernateTemplate().setCacheQueries(false);
    		return hds;
    	}


        调用这个方法,针对同一sql来讲,只发送一条sql,下次查询直接从缓存中获取。
    注:this.getHibernateTemplate().setCacheQueries(true);后最好是要this.getHibernateTemplate().setCacheQueries(false),来关闭查询缓存,因为实际应用中,不可能所有的查询我们都得设置缓存。
    分享到:
    评论

    相关推荐

      Hibernate二级缓存(Ehcache)

      【标题】:“Hibernate二级缓存(Ehcache)” 【正文】: Hibernate是一个流行的Java对象关系映射(ORM)框架,它允许开发者用面向对象的方式来处理数据库操作。然而,随着应用规模的扩大,性能优化变得至关重要,...

      Hibernate4二级缓存Ehcache案例

      在这个“Hibernate4二级缓存Ehcache案例”中,我们将深入探讨如何利用Ehcache作为Hibernate的二级缓存提供商,以提升应用性能。 首先,我们需要了解什么是二级缓存。一级缓存是Hibernate Session级别的缓存,每个...

      springmvc4+spring4+hibernate5.1.3+二级缓存ehcache+fastjson配置

      Ehcache是Hibernate的一个可选二级缓存插件,用于存储数据库查询结果,减少对数据库的直接访问。当相同的数据再次被请求时,可以从缓存中快速获取,提高系统响应速度。在不使用缓存的情况下,可以通过配置关闭。 5...

      hibernate二级缓存包

      在本压缩包“hibernate二级缓存包”中,重点包含的是 Ehcache 这个流行且广泛使用的二级缓存实现。 Ehcache 是一个开源的、高性能的缓存解决方案,它可以被集成到各种Java应用中,包括Hibernate框架。Ehcache 提供...

      hibernate二级缓存实例

      2. 配置Hibernate:在hibernate.cfg.xml文件中启用二级缓存,并指定使用Ehcache作为二级缓存提供者。 3. 配置实体类:在实体类上使用`@Cacheable`、`@Cache`等注解,声明该类及属性参与缓存。 4. 配置缓存策略:...

      hibernate一级缓存和二级缓存的区别与联系

      二级缓存可以是内存中的缓存,也可以扩展到硬盘,例如使用第三方缓存提供商(如 EhCache 或者 Infinispan)。二级缓存中存储的是对象的集合数据,而不是单个对象实例,这样可以更高效地处理大量数据。二级缓存可以...

      Hibernate二级缓存

      1. **导入依赖**:首先,你需要添加ehcache库的jar包到项目的类路径中,因为Hibernate通常使用ehcache作为默认的二级缓存提供者。 2. **配置二级缓存**:在`hibernate.cfg.xml`配置文件中,需要指定二级缓存的提供...

      Hibernate中二级缓存ehcache缓存案例

      2. **配置hibernate.cfg.xml**:在Hibernate的配置文件中,开启二级缓存支持并指定使用ehcache。添加以下配置: ```xml &lt;property name="hibernate.cache.use_second_level_cache"&gt;true &lt;property name="...

      hibernate二级缓存示例源码

      在Hibernate配置文件(hibernate.cfg.xml)中,我们需要添加二级缓存插件的相关配置,例如Ehcache: ```xml &lt;property name="hibernate.cache.region.factory_class"&gt;org.hibernate.cache.ehcache....

      hibernate一级缓存、二级缓存和查询缓存

      **hibernate一级缓存、二级缓存和查询缓存** 在Java的持久化框架Hibernate中,缓存机制是提高应用程序性能的关键要素。缓存能够减少数据库的访问次数,提高数据读取速度,并且在一定程度上降低了系统的负载。本文将...

      day37 05-HIbernate二级缓存:一级缓存更新同步到二级缓存及二级缓存配置文件

      本篇文章将深入探讨Hibernate的二级缓存机制,以及如何进行一级缓存与二级缓存的同步,同时还会介绍二级缓存的配置文件设置。 一级缓存是Hibernate默认提供的缓存,每个SessionFactory实例都有一个一级缓存。当对象...

      hibernate 二级缓存详解

      在Hibernate中,二级缓存可以使用不同的提供商,例如Ehcache和OSCache。配置Ehcache作为二级缓存提供商,需要在Hibernate的配置文件中设置`hibernate.cache.provider_class`为`...

      hibernate二级缓存

      Hibernate 二级缓存是一种高效的数据存储机制,它能够显著提升Web应用的性能,尤其是在处理大量数据流动时。缓存的主要目标是减少应用与数据库之间的交互次数,从而降低延迟并减轻数据库服务器的压力。在Hibernate...

      hibernate二级缓存所需要的 jar包

      1. **ehcache-core.jar**:Ehcache是Hibernate常用的二级缓存提供商。它是一个开放源代码的Java分布式缓存,提供了内存和磁盘存储、缓存过期策略等功能。在Hibernate中配置Ehcache,可以实现高效的二级缓存服务。 2...

      为Spring集成的Hibernate配置二级缓存

      2. **配置Hibernate**:在Hibernate的配置文件`hibernate.cfg.xml`中启用二级缓存并指定缓存提供商。以下是一个使用Ehcache的示例: ```xml &lt;property name="hibernate.cache.use_second_level_cache"&gt;true ...

      hibernate二级缓存java包下载

      二级缓存是 Hibernate 缓存策略的一部分,它在应用程序的多个会话之间共享数据,进一步优化了数据库访问效率。 二级缓存分为以下关键知识点: 1. **一级缓存与二级缓存的区别**: - 一级缓存:每个 Hibernate ...

      Spring集成的Hibernate配置二级缓存

      以EhCache为例,我们需要在项目中引入ehcache-core或ehcache的依赖,并在Hibernate配置文件(hibernate.cfg.xml或persistence.xml)中启用二级缓存,添加如下配置: ```xml &lt;property name="hibernate.cache.use_...

      Hibernate一级缓存和二级缓存

      标题“Hibernate一级缓存和二级缓存”指的是Hibernate框架中的两种缓存机制,它们是提高数据访问性能的关键要素。一级缓存是Session级别的,而二级缓存是SessionFactory级别的,两者在数据库操作中起到了重要的作用...

      springboot+jpa(hibernate配置redis为二级缓存) springboot2.1.4

      在本文中,我们将深入探讨如何在Spring Boot 2.1.4.RELEASE项目中结合JPA(Java Persistence API)和Hibernate实现Redis作为二级缓存。首先,我们需要理解这些技术的基本概念。 Spring Boot 是一个用于简化Spring...

      Hibernate 二级缓存 总结整理

      2. **缓存提供者(Cache Provider)**:Hibernate通过缓存提供者来实现二级缓存,常见的有Ehcache、Infinispan等。缓存提供者负责存储和检索数据,以及缓存的同步和过期策略。 3. **缓存策略(Cache Strategy)**:...

    Global site tag (gtag.js) - Google Analytics