在Spring中使用Cache缓存方法返回

刚好在项目中用到了Spring中的Cache缓存服务层方法的返回值

使用相当简单,直接用@Cacheable注解标注需要缓存返回值的方法,如下

@Cacheable(value = "billfoldCache", key = "'fetchByGroupName' + #groupName")
Collection<Game> fetchByGroupName(final String groupName) {
}

其中value的值是缓存的名字,在ehcache配置文件中指定(如果使用ehcache作为底层缓存),key是缓存的键,并支持Spring Expression Language (SpEL)。

配置
目前Spring中带了两种实现,一是基于ehcache,另一个是基于Java中的ConcurrentMap实现。项目是使用的是ehcache

配置也很简单,在Spring配置文件中加入

    <cache :annotation-driven cache-manager="billfoldCacheManager"></cache>
 
    <bean id="billfoldCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
          p:cacheManager-ref="billfoldEhCacheManagerFactoryBean"></bean>
 
    <bean id="billfoldEhCacheManagerFactoryBean"
          class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
          p:configLocation="classpath:/ctx-ehcache.xml"></bean>

并且为ehcache创建名为ctx-ehcache.xml的配置文件

< ?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false">
    <diskstore path="java.io.tmpdir"></diskstore>
    <defaultcache maxEntriesLocalHeap="100000" eternal="false"
                  timeToIdleSeconds="120" timeToLiveSeconds="120" maxEntriesLocalDisk="1000000"
                  diskExpiryThreadIntervalSeconds="3600" memoryStoreEvictionPolicy="LFU">
    </defaultcache>
 
    <cache name="billfoldCache" eternal="false" maxEntriesLocalHeap="100000"
           timeToLiveSeconds="60" timeToIdleSeconds="60">
        <persistence strategy="none"></persistence>
    </cache>
</ehcache>

需要注意的是:

  • Spring推荐在实现类上使用@Cache*注解,而不是在接口上使用
  • 在默认的配置下(proxy),@Cache*只对外部调用具有public可见性的方法起作用,protected, private, package-visible以及内部方法调用,缓存都不会生效。除非使用在配置时明确指定mode为aspectj。详细见Spring CacheSpring Configuration – load time weaver

发表评论

邮箱地址不会被公开。 必填项已用*标注