参考文献:
http://blog.csdn.net/fengshizty/article/details/43603611 (Hibernate二级缓存以及ehcache的搭建配置)
http://www.cnblogs.com/WJ-163/p/5845446.html (Hibernate二级缓存配置)
http://blog.csdn.net/defonds/article/details/2308972 (hibernate一级缓存和二级缓存的区别)
一、概念
二级缓存是SessionFactory级别的。由SessionFactory对象负责管理。通过Factory创建的Session都可以访问二级缓存。二级缓存默认是关闭的。如果二级缓存打开,则先去一级缓存找对象,找不到则去二级缓存,还找不到则访问数据库。
二、使用范围
什么样的数据适合存放到第二级缓存中?
1:很少被修改的数据
2:不是很重要的数据,允许出现偶尔并发的数据
3:不会被并发访问的数据
4:常量数据
不适合存放到第二级缓存的数据?
1:经常被修改的数据
2:绝对不允许出现并发访问的数据,如财务数据,绝对不允许出现并发
3:与其他应用共享的数据。
三、二级缓存配置
1:配置关键jar包
(1)Ehcache-core包
<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache-core -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.11</version>
</dependency>
(2)Hibernate-Ehcache包
因为要与Hibernate匹配使用,所以要根据Hibernate的版本来下载Ehcache插件包。例如hibernate-core的版本是3.3.2.GA,所以对应的hibernate-ehcache也是3.3.2.GA。
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-ehcache -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>3.3.2.GA</version>
</dependency>
2:在Hibernate的配置文件中设置二级缓存的相关信息
<!-- 配置二级缓存 -->
<!-- 开启二级缓存 ehcache -->
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<!-- 开启查询的二级缓存 如果不需要就不设置-->
<prop key="hibernate.cache.use_query_cache">true</prop>
<!-- Hibernate4.0以上设置factory -->
<!-- <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop> -->
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<!-- 二级缓存 ehcache的配置文件位置 -->
<prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</prop>
一般Hibernate的二级缓存实体和属性的缓存映射,如果需要将查询数据也二级缓存,需要使用hibernate.cache.use_query_cache开启。
另附上我配置的spring-hibernate.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<description>持久层配置文件 </description>
<!-- 定义受环境影响易变的变量 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath*:datasource.properties</value>
</list>
</property>
</bean>
<!-- 配置c3p0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="3"/>
<!--初始化时获取连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="5"/>
<property name="minPoolSize" value="3"/>
<property name="maxPoolSize" value="100"/>
<!--最大空闲时间,30秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="30"/>
<!--每30秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod" value="30"/>
<property name="maxStatements" value="5000"/>
<property name="numHelperThreads" value="3"/>
</bean>
<!-- Annotation 配置sessionFactory,配置数据库连接,注入hibernate数据库配置 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.ssh.entity"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!-- 链接释放策略 on_close | after_transaction | after_statement | auto -->
<prop key="hibernate.connection.release_mode">after_transaction</prop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<!--prop key="hibernate.hbm2ddl.auto">update</prop-->
<!-- 配置二级缓存 -->
<!-- 开启二级缓存 ehcache -->
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<!-- 开启查询的二级缓存 如果不需要就不设置-->
<prop key="hibernate.cache.use_query_cache">true</prop>
<!-- Hibernate4.0以上设置factory -->
<!-- <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop> -->
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<!-- 二级缓存 ehcache的配置文件位置 -->
<prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</prop>
</props>
</property>
<property name="namingStrategy" >
<bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
</property>
</bean>
<!-- 事务管理器配置,单数据源事务 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置事务的传播特性 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:advisor advice-ref="transactionAdvice" pointcut="execution(* com.ssh.biz..*.*(..))"/>
</aop:config>
</beans>
3:ehcache.xml的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="D:/ehcache" />
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="300"
maxElementsOnDisk="1000000"
overflowToDisk="true"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
配置详解
name:缓存名称。
maxElementsInMemory:缓存最大个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
maxElementsOnDisk:硬盘最大缓存个数。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
存储位置配置(自定义配置路径)
<diskStore path="D:/ehcache" />
ehcache.xml配置文件放到了src目录下,其实可自己定义配置目录。
<!-- 二级缓存 ehcache的配置文件位置 -->
<prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</prop>
四、配置需二级缓存实体和属性(注解形式)
在实体类和实体的那些集合属性上启用二级缓存使用
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
package com.ssh.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Table(name = "user_base_info" )
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class UserBaseInfo implements Serializable{
private static final long serialVersionUID = -1948330516997216009L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "cellphone")
private String cellphone;
@Column(name = "name")
private String name;
@Column(name = "status")
private Integer status;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Temporal(value = TemporalType.TIMESTAMP)
@Column(name = "create_time")
private Date createTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
@Cache配置 http://blog.csdn.net/w410589502/article/details/54603265