每一次实践得出结论,得出的对过往理论的印证,都是一次悟道,其收益远大于争论和抱怨。
技术是一件比较客观的事,正确与错误,其实就摆在哪里,意见不统一,写段代码试验一下就好了,一段代码印证不了的时候,就多写几段。
先同一个案例说起
挺简单的一个案例,通过SpringAOP和注解,使用Guava缓存。代码如下:
GuavaCache.java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface GuavaCache {
/**
* group : 一个group代表一个cache,不传或者""则使用 class+method 作为cache名字
* @return
*/
public String group() default "";
/**
* key : 注意,所有参数必须实现GuavaCacheInterface接口,如果不实现,则会用toString()的MD5作为Key
* @return
*/
public String key() default "";
/**
* 过期时间,缺省30秒
* @return
*/
public long timeout() default 30;
/**
* 缓存最大条目,缺省10000
* @return
*/
public long size() default 10000;
/**
* 是否打印日志
* @return
*/
public boolean debug() default false;
}
GuavaInterface.java
/**
* 使用GuavaCache注解时,如果传入参数是对象,则必须实现这个类
*
*/
public interface GuavaCacheInterface {
public String getCacheKey();
}
GuavaCacheProcessor.java
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect