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!