美文网首页
二级缓存

二级缓存

作者: 闫子扬 | 来源:发表于2017-10-12 15:18 被阅读0次

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

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

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

二级缓存

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

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

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

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

缓存的级别

1.事务级缓存(translation) 、 性能低

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

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

  • 很少被修改的数据
  • 不重要的数据

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

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

集成步骤

1.导入对应的jar包
2.配置applicationContext.xml设置开启二级缓存

                <!-- 开启二级缓存 -->
            <prop key="hibernate.cache.use_second_level_cache">true</prop>
            <!-- 查询结果缓存 -->
            <prop key="hibernate.cache.use_query_cache">true</prop>
            <!-- 设置缓存提供商 -->
            <prop key="hibernate.cache.region.factory_class">
                org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
            </prop>

3.配置ehcache.xml 文件说明缓存方案

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <!-- 配置文件缓存溢出后存储位置 -->
    <diskStore path="c:/ehcache"/>
    <!-- maxElementsInMemory 缓存最多个数 
         eternal:对象永久有效,一旦设置为true,那么timeout就无效
         timeToIdleSeconds:设置对象失效前,空闲的最大时间。当设置eternal="false",才能起效
         timeToliveSeconds:设置对象失效前可以存活多少秒。设置0,表示永久有效
         overflowToDisk:溢出时写入硬盘
    -->
    <defaultCache maxElementsInMemory="10000" eternal="false" 
    timeToIdleSeconds="120" timeToliveSeconds="120" overflowToDisk="true"/>
</ehcache>

4.查询缓存,要在代码中设置开启查询缓存

this.getHibernateTemplate().setCacheQueries(true);

5.可以自定义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>

相关文章

网友评论

      本文标题:二级缓存

      本文链接:https://www.haomeiwen.com/subject/fjqoyxtx.html