hibernate 二级缓存

缓存:介于应用程序和永久存储介质(硬盘,U盘,磁带,刻录CD)之间,其作用是将降低应用程序和硬盘介质的直接读写频率。从而提升应用程序的性能,缓存一般是在内存中。

数据库缓存:要减少与数据库间的频繁操作。可以大大提升数据访问速度。

缓存: 应用程序–(缓存(内存))–硬盘


二级缓存

  • 在hibernate中一级缓存就是session级别的缓存,在同一次请求中共享数据
  • hibernate中二级缓存就是sessionFactory,整个应用程序共享一个会话工厂,共享一个二级缓存

  • sessionFactory缓存分为两部分:

    1. 内置缓存:内部会使用一个map,用于存储配置信息,存储预定义hql语句。 只读
    2. 外置缓存:用于存储用户自定义数据,默认未开启,外置缓存hibernate只提供了规范(接口),并为实现,需要借助第三方类。可读写

二级缓存,可以缓存的内容

  1. 类级别缓存
  2. 集合级别缓存
  3. 时间戳缓存
  4. 缓存查询结果

缓存的级别

  1. 事务级缓存(translation) 、性能低
  2. 读写缓存(read-write) 、使用经常读,很少写的环境,更新时会锁定缓存中数据
  3. 只读型 (rea-only) 、从来不会被修改的数据,做更新会出现异常
  4. 非严格读写(nonstrict-read-write)、更新时不锁定数据,容易脏读写。

缓存应用场景–适合放入二级缓存的数据

  1. 很少被修改的数据
  2. 不重要的数据

二级缓存常见供应商(第三方缓存)

  1. ehcache,支持集群,不支持事务级缓存
  2. jbosscache
  3. swamecache
  4. openSymphony

集成步骤

  1. 导入对应的jar包
  2. 配置applicationContext.xml设置开启二级缓存
    这里写图片描述
  3. 配置ehcache.xml
<ehcache>
    <!-- 配置文件缓存溢出后位置 -->
    <diskStore path="c:/chcache"/>
    <!-- maxElementsInMemory 表示缓存的最多个数 
         eternal 对象永久有效,一旦设置为true,nametimeout就无效
         timeToIdleSeconds 设置对象失效前,空闲的最大时间,当设置eternal="false",才能起效
         timeToLiveSeconds 设置对象失效前,可以存活多少秒,设置0,表示永久有效
         overflowToDisk 溢出时写入硬盘
    -->
    <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"/>
</ehcache>
  1. 查询缓存,要在代码中设置开启查询缓存
this.getHibernateTemplate().setCacheQueries(true);
  1. 可以自定义hibernateTemplate
<!-- sping4托管hibernate5通过hibernateTemplate -->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"></property>
        <property name="cacheQueries" value="true"></property>
    </bean>

    <!-- 配置dao层 -->
    <bean id="movieDao" class="cn.com.dao.impl.MovieDaoImpl">
        <property name="hibernateTemplate" ref="hibernateTemplate"></property>
    </bean>

猜你喜欢

转载自blog.csdn.net/arrogance_qi/article/details/78200843