Java開辟框架spring完成自界說緩存標簽。本站提示廣大學習愛好者:(Java開辟框架spring完成自界說緩存標簽)文章只能為提供參考,不一定能成為您想要的結果。以下是Java開辟框架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注解辦法
*/
@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辦法的切面
*/
@Aspect
public class CacheAspect {
private Logger logger = Logger.getLogger(CacheAspect.class);
private Map<String, Object> cache;
public CacheAspect() {
cache = new HashMap<String, Object>();
}
/**
* 一切標注了@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;
public class Calculator {
private Logger logger = Logger.getLogger(Calculator.class);
@MyCacheable
public 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設置裝備擺設以下:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<aop:aspectj-autoproxy />
<bean class="caching.springaop.CacheAspect" />
<bean id="calc" class="caching.springaop.Calculator" />
</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");
//盤算出來的成果將會被存儲在cache
logger.info("1 + 2 = " + calc.sum(1, 2));
//從緩存中獲得成果
logger.info("1 + 2 = " + calc.sum(1, 2));
logger.debug("Finished!");
}
}
我們看一下運轉的成果:
從成果來看第一次直接盤算成果,第二次從緩存中獲得。
以上就是spring完成自界說緩存標簽的全體內容,願望對年夜家的進修有所贊助