Spring中@Cacheable的用法


在Spring中通過獲取MemCachedClient來實現與memcached服務器進行數據讀取的方式。不過,在實際開發中,我們往往是通過Spring的@Cacheable來實現數據的緩存的,所以,本文給大家詳細介紹一下@Cacheable的用法。首先,在使用@Cacheable之前,我們要做好准備工作。

第一步:要導入相應的jar包。
   <classpathentry kind="lib" path="lib/spring-core-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/spring-cache-1.0.10.jar"/>
    <classpathentry kind="lib" path="lib/spring-context-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/spring-beans-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/commons-logging-1.2.jar"/>
    <classpathentry kind="lib" path="lib/log4j-1.2.17.jar"/>
    <classpathentry kind="lib" path="lib/spring-expression-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/java_memcached-release_2.0.1.jar"/>
    <classpathentry kind="lib" path="lib/spring-aop-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/spring-aspects-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/spring-context-support-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/spring-tx-4.1.4.RELEASE.jar"/>
    <classpathentry kind="lib" path="lib/aopalliance-1.0.jar"/>
    <classpathentry kind="lib" path="lib/ognl-3.0.6.jar"/>
    <classpathentry kind="lib" path="lib/trafficCounter-1.0.2.jar"/>
    <classpathentry kind="lib" path="lib/aspectjweaver-1.8.4.jar"/>
    <classpathentry kind="lib" path="lib/javassist-3.11.0.GA.jar"/>

第二步:xml文件中增加命名空間。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
     http://www.springframework.org/schema/context  
     http://www.springframework.org/schema/context/spring-context-3.0.xsd  
     http://www.springframework.org/schema/tx  
     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop 
     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

第三步:添加自動掃描功能。

<context:component-scan base-package="service" />
<aop:config proxy-target-class="true"/>

第四步:增加緩存管理類。

<bean id="memCacheProvider" class="com.springcache.memcache.MemCacheProvider">
        <property name="memCache" ref="memCacheClient"/>
</bean>
<bean id="cacheManager" class="com.springcache.CacheManager">
        <property name="elParserName" value="ognl"/>
        <property name="cacheProviders">
        <map>
        <entry key="remote" value-ref="memCacheProvider"></entry>
        </map>
        </property>
</bean>

第五步:建立一個測試類。

package service;
import org.springframework.stereotype.Service;
import com.springcache.annotation.Cacheable;
@Service
@Cacheable
public class MemcachedService {
    @Cacheable(name = "remote", key = "'USER_NAME_'+#args[0]", expire = 60 )
    public String storeUserName(String accountId, String name)
    {
        return name;
    }
    @Cacheable(name = "remote", expire = 60)
    public String storeUserAddress(String accountId, String address)
    {
        return address;
    }
}

@Cacheable支持如下幾個參數:
key:緩存的key,默認為空,既表示使用方法的參數類型及參數值作為key,支持SpEL。例如:memCachedService.storeUserAddress("user", "BeiJing");
        所以對應的key為:service.MemcachedService-storeUserAddress_user_BeiJing
name:存儲位置。在本來中remote表示使用memcached服務器。
condition:觸發條件,只有滿足條件的情況才會加入緩存,默認為空,既表示全部都加入緩存,支持SpEL。
expire:過期時間,單位為秒。

第六 擴展:使用Spring4.3解決緩存過期后多線程並發訪問數據庫的問題

緩存過期之后,如果多個線程同時請求對某個數據的訪問,會同時去到數據庫,導致數據庫瞬間負荷增高。Spring4.3為@Cacheable注解提供了一個新的參數“sync”(boolean類型,缺省為false),

當設置它為true時,只有一個線程的請求會去到數據庫,其他線程都會等待直到緩存可用。這個設置可以減少對數據庫的瞬間並發訪問。

不過不一定所有的緩存系統都支持這個配置。經過驗證,Guava Cache是支持的  參考:http://blog.csdn.net/clementad/article/details/51250472

@Service  
public class UserServiceCacheablesImpl implements UserServiceCacheables{  
    private final static Logger logger = LoggerFactory.getLogger(UserServiceCacheablesImpl.class);  
  
    @Autowired  
    UserDAO userDAO;  
      
    @Override  
   @Cacheable(value="getPhoneNoByUserId", sync=true)  
    public String getPhoneNoByUserId(int userId) {  
        logger.debug("getting data from database, userId={}", userId);  
        return userDAO.getPhoneNoByUserId(userId);  
    }  
}  

 


最后總結一下:當執行到一個被@Cacheable注解的方法時,Spring首先檢查condition條件是否滿足,如果不滿足,執行方法,返回;如果滿足,在name所命名的緩存空間中查找使用key存儲的對象,如果找到,將找到的結果返回,如果沒有找到執行方法,將方法的返回值以key-value對象的方式存入name緩存中,然后方法返回。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM