合理的使用缓存策略,往往在web开发中提高性能起到关键作用。
为Spring集成的Hibernate配置二级缓存 步骤:
1.修改beans.xml,加上 ,我们这里使用的EhCache,还有OSCache,JBossCache 也可以使用
<!-- 打开hibernate的二级缓存 -->
hibernate.cache.use_second_level_cache=true
<!-- 是否使用查询缓存 -->
hibernate.cache.use_query_cache=false
<!-- 使用缓存产品的驱动类 -->
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
- <?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:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
- <context:annotation-config/>
- <!-- 隐式的注入spring的一些bean处理器 比如
- AutowiredAnnotationBeanPostProcessor
- CommonAnnotationBeanPostProcessor
- ersistenceAnnotationBeanPostProcessor
- equiredAnnotationBeanPostProcessor
- -->
- <!-- 1.配置数据源 -->
- <context:property-placeholder location="classpath:jdbc.properties"/>
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
- <property name="driverClassName" value="${driverClassName}"/>
- <property name="url" value="${url}"/>
- <property name="username" value="${username}"/>
- <property name="password" value="${password}"/>
- <!-- 连接池启动时的初始值 -->
- <property name="initialSize" value="${initialSize}"/>
- <!-- 连接池的最大值 -->
- <property name="maxActive" value="${maxActive}"/>
- <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
- <property name="maxIdle" value="${maxIdle}"/>
- <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
- <property name="minIdle" value="${minIdle}"/>
- </bean>
- <!-- 2.配置 sessionFactory,让spring容器来管理-->
- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
- <property name="dataSource" ref="dataSource"/>
- <property name="mappingResources">
- <list>
- <value>cn/com/xinli/bean/Person.hbm.xml</value>
- </list>
- </property>
- <property name="hibernateProperties">
- <value>
- hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
- <!-- 表示使用根据映射元数据生成表结构 -->
- hibernate.hbm2ddl.auto=update
- hibernate.show_sql=true
- hibernate.format_sql=true
- <!-- 打开hibernate的二级缓存 -->
- hibernate.cache.use_second_level_cache=true
- <!-- 是否使用查询缓存 -->
- hibernate.cache.use_query_cache=false
- <!-- 使用缓存产品的驱动类 -->
- hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
- </value>
- </property>
- </bean>
- <!-- 3.配置事务管理器,用来管理 sessionFactory创建的session-->
- <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
- <property name="sessionFactory" ref="sessionFactory"/>
- </bean>
- <!-- 4.配置事务管理器的实现方式 注解 -->
- <tx:annotation-driven transaction-manager="txManager"/>
- <bean id="personService" class="cn.com.xinli.service.impl.PersonServiceBean"/>
- <bean name="/list" class="cn.com.xinli.web.action.PersonAction"/>
- </beans>
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config/>
<!-- 隐式的注入spring的一些bean处理器 比如
AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor
ersistenceAnnotationBeanPostProcessor
equiredAnnotationBeanPostProcessor
-->
<!-- 1.配置数据源 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="${initialSize}"/>
<!-- 连接池的最大值 -->
<property name="maxActive" value="${maxActive}"/>
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="${maxIdle}"/>
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="${minIdle}"/>
</bean>
<!-- 2.配置 sessionFactory,让spring容器来管理-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>cn/com/xinli/bean/Person.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
<!-- 表示使用根据映射元数据生成表结构 -->
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true
<!-- 打开hibernate的二级缓存 -->
hibernate.cache.use_second_level_cache=true
<!-- 是否使用查询缓存 -->
hibernate.cache.use_query_cache=false
<!-- 使用缓存产品的驱动类 -->
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
</value>
</property>
</bean>
<!-- 3.配置事务管理器,用来管理 sessionFactory创建的session-->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 4.配置事务管理器的实现方式 注解 -->
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="personService" class="cn.com.xinli.service.impl.PersonServiceBean"/>
<bean name="/list" class="cn.com.xinli.web.action.PersonAction"/>
</beans>
2.*.hbm.xml 中
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping package="cn.com.xinli.bean">
- <class name="Person" table="person">
- <!-- 增加缓存支持 -->
- <cache usage="read-write" region="cn.com.xinli.bean.Person"/>
- <id name="id" type="int">
- <!-- Native主键生成方式会根据不同的底层数据库自动选择
- Identity、Sequence、Hilo主键生成方式,这里使用的是mysql
- 则主键的生成方式为自增长。
- -->
- <generator class="native"/>
- </id>
- <property name="name" length="10" not-null="true"/>
- </class>
- </hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.com.xinli.bean">
<class name="Person" table="person">
<!-- 增加缓存支持 -->
<cache usage="read-write" region="cn.com.xinli.bean.Person"/>
<id name="id" type="int">
<!-- Native主键生成方式会根据不同的底层数据库自动选择
Identity、Sequence、Hilo主键生成方式,这里使用的是mysql
则主键的生成方式为自增长。
-->
<generator class="native"/>
</id>
<property name="name" length="10" not-null="true"/>
</class>
</hibernate-mapping>
3.配置EHcache的配置文件 ehcache.xml(放在类路径下)
- <?xml version="1.0" encoding="UTF-8"?>
- <!--
- defaultCache节点为缺省的缓存策略
- maxElementsInMemory 内存中最大允许存在的对象数量
- eternal 设置缓存中的对象是否永远不过期
- overflowToDisk 把溢出的对象存放到硬盘上
- timeToIdleSeconds 指定缓存对象空闲多长时间就过期,过期的对象会被清除掉
- timeToLiveSeconds 指定缓存对象总的存活时间
- diskPersistent 当jvm结束是是否持久化对象
- diskExpiryThreadIntervalSeconds 指定专门用于清除过期对象的监听线程的轮询时间
- -->
- <ehcache>
- <diskStore path="D:\cache"/>
- <defaultCache maxElementsInMemory="1000" eternal="false" overflowToDisk="true"
- timeToIdleSeconds="120"
- timeToLiveSeconds="180"
- diskPersistent="false"
- diskExpiryThreadIntervalSeconds="60"/>
- <cache name="cn.itcast.bean.Person" maxElementsInMemory="100" eternal="false"
- overflowToDisk="true" timeToIdleSeconds="300" timeToLiveSeconds="600" diskPersistent="false"/>
- </ehcache>
<?xml version="1.0" encoding="UTF-8"?>
<!--
defaultCache节点为缺省的缓存策略
maxElementsInMemory 内存中最大允许存在的对象数量
eternal 设置缓存中的对象是否永远不过期
overflowToDisk 把溢出的对象存放到硬盘上
timeToIdleSeconds 指定缓存对象空闲多长时间就过期,过期的对象会被清除掉
timeToLiveSeconds 指定缓存对象总的存活时间
diskPersistent 当jvm结束是是否持久化对象
diskExpiryThreadIntervalSeconds 指定专门用于清除过期对象的监听线程的轮询时间
-->
<ehcache>
<diskStore path="D:\cache"/>
<defaultCache maxElementsInMemory="1000" eternal="false" overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="180"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="60"/>
<cache name="cn.itcast.bean.Person" maxElementsInMemory="100" eternal="false"
overflowToDisk="true" timeToIdleSeconds="300" timeToLiveSeconds="600" diskPersistent="false"/>
</ehcache>
测试: 首先使用getBean 从数据库得到一个Person对象,线程终止10秒,在掉getBean ,期间去关闭数据库,如果还能得到Person 对象,则认为第2次得到的Person 对象是从缓存中得到的
测试用例
- @Test
- public void testGetPersonP()
- {
- Person person=perService.getPerson(new Integer(1));
- System.out.println("id:"+person.getId());
- System.out.println("name:"+person.getName());
- System.out.println("请关闭数据库...");
- try {
- Thread.sleep(10000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Person person2=perService.getPerson(new Integer(1));
- System.out.println("id:"+person2.getId());
- System.out.println("name:"+person2.getName());
- }
@Test
public void testGetPersonP()
{
Person person=perService.getPerson(new Integer(1));
System.out.println("id:"+person.getId());
System.out.println("name:"+person.getName());
System.out.println("请关闭数据库...");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Person person2=perService.getPerson(new Integer(1));
System.out.println("id:"+person2.getId());
System.out.println("name:"+person2.getName());
}
结果:
- Hibernate:
- select
- person0_.id as id0_0_,
- person0_.name as name0_0_
- from
- person person0_
- where
- person0_.id=?
- id:1
- name:胡晓亮
- 请关闭数据库...
- id:1
- name:胡晓亮
Hibernate:
select
person0_.id as id0_0_,
person0_.name as name0_0_
from
person person0_
where
person0_.id=?
id:1
name:胡晓亮
请关闭数据库...
id:1
name:胡晓亮
可见缓存生效了。。