首先,寫一個簡單的緩存註解:java
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Cache { public String key(); public int expire() default 600; }
假設有一個數據訪問的類:spring
import cn.freemethod.annotation.Cache; public class DaoService { @Cache(key="#hash(#args1,#args2)") public void getData(String name,int id) { System.out.println("access data"); } }
緩存的工具類 :express
import java.lang.reflect.Method; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import cn.freemethod.annotation.Cache; public class CacheUtil { public static void dealCacheAnnotation(Class<?> clazz) { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); Method[] methods = clazz.getDeclaredMethods(); Method[] ms = CacheUtil.class.getDeclaredMethods(); Method method = null; for(Method m:ms) { if("hash".equalsIgnoreCase(m.getName())) { method = m; break; } } for(Method m:methods) { if(m.isAnnotationPresent(Cache.class)) { Cache cacheAnnotation = m.getAnnotation(Cache.class); String key = cacheAnnotation.key(); Expression expression = parser.parseExpression(key); context.registerFunction("hash", method); Class<?>[] parameterTypes = m.getParameterTypes(); for(int i= 0;i<parameterTypes.length;i++) { ////生成key的方法很差,重複太多 context.setVariable("args"+(i+1), parameterTypes[i].getName()); } String value = expression.getValue(context,String.class); System.out.println(value); System.out.println(value.length()); } } } public static String hash(String... strings) { StringBuffer sb = new StringBuffer(); for(String s:strings) sb.append(s); String tmp = sb.toString(); sb = new StringBuffer(); for(int i=0;i<tmp.length();i++) sb.append((int)tmp.charAt(i)); return sb.substring(0, 20);//sb.toString(); } public static void main(String[] args) { dealCacheAnnotation(DaoService.class); } }