spring自訂緩衝標籤的實現

來源:互聯網
上載者:User

spring自訂緩衝標籤的實現

自從spring3.1之後,spring引入了抽象緩衝,可以通過在方法上添加@Cacheable等標籤對方法返回的資料進行緩衝。但是它到底是怎麼實現的呢,我們通過一個例子來看一下。首先我們定義一個@MyCacheable

package caching.springaop;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.lang.annotation.ElementType;/** * 使用@MyCacheable註解方法 * @author txxs */@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface MyCacheable{}

然後定義處理MyCacheable的切面
package caching.springaop;import java.util.HashMap;import java.util.Map;import org.apache.log4j.Logger;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;/** * 處理MyCacheable方法的切面 * @author txxs */@Aspectpublic class CacheAspect {private Logger logger = Logger.getLogger(CacheAspect.class);private Map cache;public CacheAspect() {cache = new HashMap();}/** * 所有標註了@Cacheable標籤的方法切入點 */@Pointcut(execution(@MyCacheable * *.*(..)))@SuppressWarnings(unused)private void cache() {}@Around(cache())public Object aroundCachedMethods(ProceedingJoinPoint thisJoinPoint)throws Throwable {logger.debug(Execution of Cacheable method catched);//產生快取資料的key值,像是這個樣子caching.aspectj.Calculator.sum(Integer=1;Integer=2;)StringBuilder keyBuff = new StringBuilder();//增加類的名字keyBuff.append(thisJoinPoint.getTarget().getClass().getName());//加上方法的名字keyBuff.append(.).append(thisJoinPoint.getSignature().getName());keyBuff.append(();//迴圈出cacheable方法的參數for (final Object arg : thisJoinPoint.getArgs()) {//增加參數的類型和值keyBuff.append(arg.getClass().getSimpleName() + = + arg + ;);}keyBuff.append());String key = keyBuff.toString();logger.debug(Key =  + key);Object result = cache.get(key);if (result == null) {logger.debug(Result not yet cached. Must be calculated...);result = thisJoinPoint.proceed();logger.info(Storing calculated value ' + result + ' to cache);cache.put(key, result);} else {logger.debug(Result ' + result + ' was found in cache);return result;}}

上述代碼展示了如何處理MyCacheable自訂的標籤,以及預設情況下產生key值的規則。最後產生的key值大概是這個樣子:caching.aspectj.Calculator.sum(Integer=1;Integer=2;)

下邊這段代碼在方法上添加了MyCacheable標籤

package caching.springaop;import org.apache.log4j.Logger;/** * 時間計算類 * @author Igor Urmincek * @author txxs */public class Calculator {private Logger logger = Logger.getLogger(Calculator.class);@MyCacheablepublic int sum(int a, int b) {logger.info(Calculating  + a +  +  + b);try {//假設這是代價非常高的計算Thread.sleep(3000);} catch (InterruptedException e) {logger.error(Something went wrong..., e);}return a + b;}}

在方法上加了MyCacheable標籤,當key值相同的情況下會直接在緩衝中擷取資料,如果沒有相同的key值,則會重新計算,因為這裡只是一個加和操作,耗時非常的短暫。我們在這裡讓其睡眠3秒鐘。

我們在spring-config.xml配置如下:

<!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D1.0%20encoding%3DUTF-8%3F%2D%2D%3E--><beans aop="" beans="" http:="" schema="" spring-aop-2.5.xsd="" spring-beans-2.5.xsd="" www.springframework.org="" xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://www.springframework.org/schema/aop"><aop:aspectj-autoproxy><bean class="caching.springaop.CacheAspect"><bean class="caching.springaop.Calculator" id="calc"></bean></bean></aop:aspectj-autoproxy></beans>
測試類別:
package caching.springaop;import org.apache.log4j.Logger;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * 使用SpringAOP緩衝的簡單例子 * @author txxs */public class App {private static Logger logger = Logger.getLogger(App.class);public static void main(String[] args) {logger.debug(Starting...);ApplicationContext ctx = new ClassPathXmlApplicationContext(spring-config.xml);Calculator calc = (Calculator) ctx.getBean(calc);//計算出來的結果將會被儲存在cachelogger.info(1 + 2 =  + calc.sum(1, 2));//從緩衝中擷取結果logger.info(1 + 2 =  + calc.sum(1, 2));logger.debug(Finished!);}}

我們看一下啟動並執行結果:

2015-12-11 10:43:26,953 [main] DEBUG caching.springaop.CacheAspect.aroundCachedMethods(CacheAspect.java:37) - Execution of Cacheable method catched
2015-12-11 10:43:26,954 [main] DEBUG caching.springaop.CacheAspect.aroundCachedMethods(CacheAspect.java:52) - Key = caching.springaop.Calculator.sum(Integer=1;Integer=2;)
2015-12-11 10:43:26,955 [main] DEBUG caching.springaop.CacheAspect.aroundCachedMethods(CacheAspect.java:55) - Result not yet cached. Must be calculated...
2015-12-11 10:43:26,978 [main] INFO caching.springaop.Calculator.sum(Calculator.java:14) - Calculating 1 + 2
2015-12-11 10:43:29,979 [main] INFO caching.springaop.CacheAspect.aroundCachedMethods(CacheAspect.java:57) - Storing calculated value '3' to cache
2015-12-11 10:43:29,979 [main] INFO caching.springaop.App.main(App.java:20) - 1 + 2 = 3
2015-12-11 10:43:29,979 [main] DEBUG caching.springaop.CacheAspect.aroundCachedMethods(CacheAspect.java:37) - Execution of Cacheable method catched
2015-12-11 10:43:29,979 [main] DEBUG caching.springaop.CacheAspect.aroundCachedMethods(CacheAspect.java:52) - Key = caching.springaop.Calculator.sum(Integer=1;Integer=2;)
2015-12-11 10:43:29,979 [main] DEBUG caching.springaop.CacheAspect.aroundCachedMethods(CacheAspect.java:60) - Result '3' was found in cache
2015-12-11 10:43:29,980 [main] INFO caching.springaop.App.main(App.java:22) - 1 + 2 = 3
2015-12-11 10:43:29,980 [main] DEBUG caching.springaop.App.main(App.java:23) - Finished!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.