spring mvc使用ehcache



需要用到的jar包

ehcache-2.7.5.jar(主程序)
ehcache-spring-annotations-1.2.0.jar(注解)
guava-r09.jar(依赖)
slf4j-api-1.6.6.jar(依赖)

配置文件

####spring配置中需要添加如下内容 头部

xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation
http://www.springframework.org/schema/cache  
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd  

<!-- 缓存配置 -->
<!-- 启用缓存注解功能(请将其配置在Spring主配置文件中) -->
<cache:annotation-driven cache-manager="cacheManager" />

<!-- Spring自己的基于java.util.concurrent.ConcurrentHashMap实现的缓存管理器(该功能是从Spring3.1开始提供的) -->
<!-- <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"> 
	<property name="caches"> <set> <bean name="myCache" class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"/> 
	</set> </property> </bean> -->

<!-- 若只想使用Spring自身提供的缓存器,则注释掉下面的两个关于Ehcache配置的bean,并启用上面的SimpleCacheManager即可 -->
<!-- Spring提供的基于的Ehcache实现的缓存管理器 -->
<bean id="cacheManagerFactory"
	class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
	<property name="configLocation" value="classpath:ehcache.xml" />
</bean>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
	<property name="cacheManager" ref="cacheManagerFactory" />
</bean>

####ehcache.xml

updateCheck="false" 不检查更新当前使用的Ehcache的版本

    eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。

    maxElementsInMemory:缓存中允许创建的最大对象数

    overflowToDisk:内存不足时,是否启用磁盘缓存。

    timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,

     两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,

     如果该值是 0 就意味着元素可以停顿无穷长的时间。

    timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,

     这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。

    memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。

    1 FIFO,先进先出

    2 LFU,最少被使用,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。

    3 LRU,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。


<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
       maxElementsInMemory="1000"
       eternal="false"
       timeToIdleSeconds="120"
       timeToLiveSeconds="120"
       overflowToDisk="false"/>
<cache name="myCache"
       maxElementsOnDisk="20000"
       maxElementsInMemory="2000"
       eternal="false"
       overflowToDisk="true"
       diskPersistent="true"/>
<cache name="cacheTest"
       maxElementsOnDisk="20000"
       maxElementsInMemory="2000"
       eternal="false"
       overflowToDisk="true"
       diskPersistent="true"/>
</ehcache>

示例代码


cache一般用在和数据库交互的地方service

示例

package com.service;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.aft.site.yey.dao.NoticeDao;
import com.aft.site.yey.entity.Notice;
import com.app.jdbc.core.ToolUtil;

/**
 * @author: yangyang 2013年10月21日 
 * @since JDK 1.6
 */
@Service("XXXNoticeService")
public class NoticeService {
    private static Log logger = LogFactory.getLog(NoticeService.class);
    @Resource(name = "XXXNoticeDao")
    private NoticeDao dao;

    /**
     * status = 0 指未删除
     * */
    @Cacheable(value = "cacheTest",key="'noticelist'")
    public List<Notice> topN(int begin, int end) {
	    LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
	    orderby.put("publish_time", "desc");
	    Map<String, String> where = new HashMap<String, String>();
	    where.put(dao.STATUS + " = ? ", dao.NORMAL_CODE.toString());
        //TODO:delete
        System.out.println("list:");
	    logger.info("[list ]");
	    return dao.find(where, orderby, begin, end);
    }

    @CacheEvict(value = "cacheTest",key="'noticelist'")
    public void delete(String id) {
        //TODO:delete
        System.out.println("delete:");
	    logger.info("delete ");
	    dao.delete(id, false);
    }

    @CacheEvict(value = "cacheTest", allEntries = true)
    public void save(Notice notice) {
	    notice.setRowid(ToolUtil.getUUID());
	    notice.setStatus(dao.NORMAL_CODE);
	    notice.setPublish_time(new Date());
	    // TODO:yeyid的获得方式
	    notice.setYey_id("123");
	    dao.insert(notice);
        //TODO:delete
        System.out.println("save:");
	    logger.info("save ");
    }

    public Notice get(String id) {
	    return dao.findById(id);
    }

    //@CachePut(value = "cacheTest",key="#notice.getRowid()")
    public void update(Notice notice) {
	    Map<String, String> set = new HashMap<String, String>();
	    LinkedHashMap<String, String> where = new LinkedHashMap<String, String>();
	    set.put("title", notice.getTitle());
	    set.put("author", notice.getAuthor());
	    set.put("content", notice.getContent());
	    where.put(dao.getIdColumnName() + "=?", notice.getRowid());
	    dao.update(set, where);
        System.out.println("update:");
	    logger.info("update ");
    }

}

使用说明

cache主要注解使用:@Cacheable,@CacheEvict,@CachePut

缓存是这样的,取值时在方法(A)调用前查一下缓存中是否有目标值,缓存存在的话直接从缓存中拿出不再去执行方法(A),这也是最基本的*@Cacheable*的概念;

缓存中有值需要更新怎么办?使用@CacheEvict来更新,这个注解的意思是删除掉缓存里面的某个值,从而达到更新缓存的效果。关于缓存更新,例如,取topN个对象,第一次取的时候比如是前1~10个,缓存中存这1~10的一个集合对象,第二次取的时候直接从缓存中拿,这没问题,现在是这样的,假设数据库中删除了1~10个元素中的任意一个值,这样数据库中的topN与缓存中的topN就不同步了,下次你在前台取topN的时候,因为缓存里面有这个对象,根据之前的介绍(取值时在方法(A)调用前查一下缓存中是否有目标值,缓存存在的话直接从缓存中拿出不再去执行方法(A)),方法A被略过,查的值不是真正的topN了,因此需要在add或者delete之后删除掉原来的缓存,保持数据一致。其他情景请自行考虑。

根据缓存的特性,如何做到既要保证方法被调用,又希望结果被缓存呢?直接使用*@CachePut*,他与@Cacheable的区别就在与方法是会被执行的。

注解里面属性解释,@Cacheable 与@CachePut一样, @CacheEvict还有和删除有关的两个属性:

  1. value:缓存的名称,在spring配置文件中定义,必须指定至少一个

    • 例如:@Cacheable(value=”mycache”) 或者 @Cacheable(value={”cache1”,”cache2”}
  2. key:缓存的key,(缓存是键值对儿)可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合

    • 例如: @Cacheable(value=”testcache”,key=”#userName”)
    • 使用字符串"'sss'"
    • 调用对象getName方法key=”#userName.getName()”
  3. condition:缓存的条件,可以为空,使用SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存

    • 例如: @Cacheable(value=”testcache”,condition=”#userName.length()>2”)
  4. allEntries:是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存

    • 例如: @CachEvict(value=”testcache”,allEntries=true)
  5. beforeInvocation:是否在方法执行前就清空,缺省为 false,如果指定为 true,则在**方法还没有执行的时候就清空缓存*,缺省情况下为false,这样如果方法执行抛出异常,则不会清空缓存

    • 例如: @CachEvict(value=”testcache”,beforeInvocation=true)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值