作为自己以后复习用,所以不会怎么详细讲解
首先要导入ehcache-core-2.4.3.jar
以下jar包和配置文件放到我的资源上
ehcache.xml的配置,注意在配置中去掉属性说明的注解
<diskStore path="java.io.tmpdir"/> //储存位置
<defaultCache
maxElementsInMemory="10000" //缓存对象上限,最多存储多少个记录对象
eternal="false" //缓存是否永不过期
timeToIdleSeconds="120" //最大的不被访问时间 单位秒 缓存创建以后,最后一次访问缓存的日期至失效之时的时间间隔
timeToLiveSeconds="120" //最大的存活时间
overflowToDisk="true" //是否允许对象被写入到磁盘
diskPersistent="false" //是否在磁盘持久化(jvm重启后仍有效)
diskExpiryThreadIntervalSeconds="120" //在磁盘缓存时间
memoryStoreEvictionPolicy="LRU"
/>
全配置策略
一、以下属性是必须的:
1、name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)。
2、maxElementsInMemory:在内存中缓存的element的最大数目。
3、maxElementsOnDisk:在磁盘上缓存的element的最大数目,默认值为0,表示不限制。
4、eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断。
5、overflowToDisk: 如果内存中数据超过内存限制,是否要缓存到磁盘上。
二、以下属性是可选的:
1、timeToIdleSeconds: 对象空闲时间,指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问。
2、timeToLiveSeconds: 对象存活时间,指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问。
3、diskPersistent: 是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false。
4、diskExpiryThreadIntervalSeconds: 对象检测线程运行时间间隔。标识对象状态的线程多长时间运行一次。
5、diskSpoolBufferSizeMB: DiskStore使用的磁盘大小,默认值30MB。每个cache使用各自的DiskStore。
6、memoryStoreEvictionPolicy: 如果内存中数据超过内存限制,向磁盘缓存时的策略。默认值LRU,可选FIFO、LFU。
三、缓存的3 种清空策略 :
1、FIFO ,first in first out (先进先出).
2、LFU , Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存。
3、LRU ,Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
spring beans.xml的配置 在session工程的bean配置里加上开启二级缓存就行
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean ">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.jdbc.fetch_size">100</prop>
<prop key="hibernate.jdbc.batch_size">50</prop>
<!-- 二级缓存配置 -->
<prop key="hibernate.cache.use_second_level_cache">true</prop> <!-- 启用二级缓存 -->
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="hibernate.cache.use_query_cache">true</prop><!-- 启用查询缓存 -->
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.socialeshop.model</value>
</list>
</property>
</bean>
hibernate log4j.properties的配置(可以无视,只是显示sql语句可以看出二级缓存有没有生效)
#xianshi sql yuju 加上这两句就行
log4j.logger.org.hibernate.SQL=trace
log4j.logger.org.hibernate.type=trace
实体的配置,因为是用的注解开发 在实体上加上以下注解即可
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
几种缓存策略
CacheConcurrencyStrategy.NONE
CacheConcurrencyStrategy.READ_ONLY ,只读模式,在此模式下,如果对数据进行更新操作,会有异常;
CacheConcurrencyStrategy.READ_WRITE ,读写模式在更新缓存的时候会把缓存里面的数据换成一个锁,其它事务如果去取相应的缓存数据,发现被锁了,直接就去数据库查询;
CacheConcurrencyStrategy.NONSTRICT_READ_WRITE ,不严格的读写模式则不会的缓存数据加锁;
CacheConcurrencyStrategy.TRANSACTIONAL ,事务模式指缓存支持事务,当事务回滚时,缓存也能回滚,只支持 JTA 环境。
显示例子,一个获取轮播图的接口
/**异步获取首页轮播图*/
public void ajaxGetAdImageList()
{
JSONObject res = null;
try{
JSONObject obj = new JSONObject();
//获取轮播图
orderby.put("orderNum", "asc");
List<AdImage> adList = dm.getListWithCache(AdImage.class,0,3,"o.isDel = ? ", new Object[]{BaseEntity.NO},orderby);
JSONArray arr = new JSONArray();
for(AdImage img : adList)
{
JSONObject temp = new JSONObject();
temp.put("imgUrl", img.getImgUrl());
temp.put("orderNum", img.getOrderNum());
temp.put("jumpType", img.getJumpType());
if(img.getJumpType() != AdImage.JUMP_TYPE_NONE) {
temp.put("jumpTypeNo", img.getJumpType());
}
arr.put(temp);
}
obj.put("imgArr", arr);
res = SimpleToof.res(0, null, obj);
}catch(Exception e)
{
e.printStackTrace();
res = SimpleToof.res(1, e.getMessage(), null);
}
WebUtil.AJAXMsg(res.toString());
}
调用的查询方法
/**模板语句 - 查询列表 - 列表*/
@SuppressWarnings("unchecked")
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public <T> List<T> getListWithCache(Class<T> entity,Integer firstindex,Integer maxresult,String whereql,Object[] queryParme,LinkedHashMap<String, String> orderby) {
String entityName = getEntityName(entity);
String orderbyql = getOrderBy(orderby);
Query query = (Query) getSession().createQuery("select o from "+entityName+" o "+ (whereql==null ? "" :"where " + whereql) + orderbyql);
query.setCacheable(true);//启用查询缓存
query.setCacheRegion("queryCacheRegion");//设置查询缓存区域(数据过期策略)
setWhereQl(query,queryParme);
setQueryResult(firstindex, maxresult, query);//设置分页
return query.list();
}