spring和ehcache整合,實現基於註解的快取實現

魔豆發表於2016-11-11

要實現基於註解的快取實現,要求Spring的版本在3.1或以上版本。

 

首先需要在spring的配置檔案中新增對快取註解的實現:

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns:context="http://www.springframework.org/schema/context"
    xmlns:cache="http://www.springframework.org/schema/cache"
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

    <context:component-scan base-package="com.xxx" />
    
    <!-- 啟用快取註解功能 -->
    <cache:annotation-driven cache-manager="ehcacheManager"/>
    <bean id="ehcacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
         <property name="configLocation" value="classpath:ehcache.xml" />
    </bean>
    <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
         <property name="cacheManager" ref="ehcacheManagerFactory" />
    </bean>

</beans>

 

ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd">
    <diskStore path="java.io.tmpdir" />
    <defaultCache name="defaultCache" maxElementsInMemory="300" timeToLiveSeconds="1800"
        eternal="false" overflowToDisk="true" />
        
        <cache name="springCache" maxElementsInMemory="300" timeToLiveSeconds="1800"
        eternal="false" overflowToDisk="true"/>
</ehcache>

 

註解的使用:

@Service
public class MyServiceImpl implements MyService {
    ......
    @Cacheable(value="springCache",key="'userlist_' + #param['username']")
    public List<Map<String, Object>> queryUserList(Map<String, Object> param)
            throws Exception {
        return userDAO.queryUserList(param);
    }
    ......
}

  新增了@Cacheable的註解,value屬性設為固定值springCache,該值對應ehcache.xml檔案中cache的name,key屬性設為快取的名稱,可以是一個固定值,比如’userlist’,也可以新增上請求方法的屬性值,比如’userlist_’ + #param[‘username’],用於確保輸入引數不同,輸出的值不同的情況。

  除了@Cacheable註解,還有@CachePut@CacheEvict兩個註解,區別在於:

  @Cacheable:如果使用@Cacheable註解,先檢查對應的快取是否存在,如果快取存在,直接取快取值返回,不再執行方法體內容;如果快取不存在,則執行方法體內容,並且將返回的內容寫入快取
  @CachePut:使用@CachePut註解和@Cacheable註解類似,只是不管對應快取是否存在,都執行方法體,並且將返回的內容寫入快取
  @CacheEvict:@CacheEvict註解表示對應快取的刪除

 

快取的使用總結:

  在讀取資料時,使用@Cacheable註解將資料加入快取
  在資料發生改變時,使用@CachePut註解更新快取
  在資料被刪除時,使用@CacheEvict註解刪除快取

相關文章