缓存:介于应用程序和永久存储介质(硬盘,U盘,磁带,刻录CD)之间,其作用是将降低应用程序和硬盘介质的直接读写频率。从而提升应用程序的性能,缓存一般是在内存中。
数据库缓存:要减少与数据库间的频繁操作。可以大大提升数据访问速度。
缓存: 应用程序–(缓存(内存))–硬盘
二级缓存
- 在hibernate中一级缓存就是session级别的缓存,在同一次请求中共享数据
hibernate中二级缓存就是sessionFactory,整个应用程序共享一个会话工厂,共享一个二级缓存
sessionFactory缓存分为两部分:
- 内置缓存:内部会使用一个map,用于存储配置信息,存储预定义hql语句。 只读
- 外置缓存:用于存储用户自定义数据,默认未开启,外置缓存hibernate只提供了规范(接口),并为实现,需要借助第三方类。可读写
二级缓存,可以缓存的内容
- 类级别缓存
- 集合级别缓存
- 时间戳缓存
- 缓存查询结果
缓存的级别
- 事务级缓存(translation) 、性能低
- 读写缓存(read-write) 、使用经常读,很少写的环境,更新时会锁定缓存中数据
- 只读型 (rea-only) 、从来不会被修改的数据,做更新会出现异常
- 非严格读写(nonstrict-read-write)、更新时不锁定数据,容易脏读写。
缓存应用场景–适合放入二级缓存的数据
- 很少被修改的数据
- 不重要的数据
二级缓存常见供应商(第三方缓存)
- ehcache,支持集群,不支持事务级缓存
- jbosscache
- swamecache
- openSymphony
集成步骤
- 导入对应的jar包
- 配置applicationContext.xml设置开启二级缓存
- 配置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>
- 查询缓存,要在代码中设置开启查询缓存
this.getHibernateTemplate().setCacheQueries(true);
- 可以自定义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>