memcached我就不多做介紹了,也就是一個分佈式緩存系統!是一個典型的NOSQL。
下面我將用spring aop來實現一個簡單的插件,來實現annotation方式,簡單方便的取得緩存
一、首先我們得定義一個annotation.
<strong>package org.xiezhaodong.spring.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface GetCacheVaule {
public String key();//key
}</strong>
因爲memcached有很多不同得客戶端,那麼我會定義一個自己的接口。讓用戶自行實現。下面就是接口,定義了一些簡單的方法
package org.xiezhaodong.spring.cache.cacheutil;
/**
* 2015-1-14
* @author xiezhaodong
*緩存接口,用戶自行實現
*/
public interface CacheSupport {
long CACHE_TIME=2*60*60;//默認緩存時間爲2小時
/**
* 加入緩存
* @param key 鍵
* @param value 值
* @return 是否成功
*/
boolean addCache(String key,Object value);
/**
* 加入緩存,並設置緩存時間
* @param key 鍵
* @param value 值
* @param time 緩存時間
* @return 是否成功
*/
boolean addCache(String key,Object value,long cacheTime);
/**
* 刪除緩存
* @param key 鍵
* @return 是否成功
*/
boolean deleteCache(String key);
/**
* 得到緩存
* @param key 鍵
* @return 返回值
*/
Object getCache(String key);
/**
* 替換緩存中對應的值
* @param key 鍵
* @param value 值
* @return 是否替換成功
*/
boolean replaceCache(String key,Object value);
}
接下來就是切面了。註釋裏面都很詳細
package org.xiezhaodong.spring.cache.aop;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.xiezhaodong.spring.annotation.GetCacheVaule;
import org.xiezhaodong.spring.cache.cacheutil.CacheSupport;
/**
* Aop切面類,實際的作用類
*
* @author xiezhaodong
*
*/
public class GetCacheAop {
private static final Log log = LogFactory.getLog(GetCacheAop.class);
private CacheSupport cacheSupport;
public void setCacheSupport(CacheSupport cacheSupport) {
this.cacheSupport = cacheSupport;
}
public Object ProxyInvoke(ProceedingJoinPoint pjp) {
log.info("invoke proxyinvoke method");
Object result = null;
// 得到運行的方法
Method method = getMethod(pjp);
Annotation[] annotations = method.getDeclaredAnnotations();
if (annotations.length == 0) {//如果不存在註解,直接執行不緩存
try {
result = pjp.proceed();
return result;
} catch (Throwable e) {
log.warn("your method " + method.getName()+ " have some errors");
}
}
// --------------------------
String cacheKey = getCacheKey(pjp, method);
result = get_or_input_cache(pjp, result, cacheKey);
return result;
}
/**
* 得到緩存或者從數據庫中查到並且放入緩存
* @param pjp
* @param result
* @param cacheKey
* @return
*/
private Object get_or_input_cache(ProceedingJoinPoint pjp, Object result,
String cacheKey) {
if (cacheKey != null) {
result = cacheSupport.getCache(cacheKey);// 得到緩存,修改result的值
if(result==null){//如果該緩存裏面沒有,得到result並緩存到緩存服務其中
try {
result=pjp.proceed();
cacheSupport.addCache(cacheKey,result);
return result;
} catch (Throwable e) {
log.warn("invoke default");
}
}
return result;//緩存存在,直接返回result
}else{//如果沒有該註解直接執行方法
try {
result=pjp.proceed();
} catch (Throwable e) {
log.warn("invoke default");
}
}
return result;
}
/**
* 取得cache 鍵值
*
* @param pjp
* @param method
* @return 返回string
*/
private String getCacheKey(ProceedingJoinPoint pjp, Method method) {
if (method.isAnnotationPresent(GetCacheVaule.class)) {
// 如果有該註解
String key = method.getAnnotation(GetCacheVaule.class).key();// 得到要緩存的鍵值
Object[] values = pjp.getArgs();// 得到順序的參數值
ParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
String[] names = discoverer.getParameterNames(method);
Map<String, Integer> map = new ConcurrentHashMap<String, Integer>();
for (int i = 0; i < names.length; i++) {
map.put(names[i], i);// 將名字和對應的序號放入hashmap
}
// 得到真正的key 、value值
try {
Integer int_value = map.get(key);// hash中沒有對應的值,表示getcachekey和名字不符合
if (int_value == null) {
log.warn("your cachekey is not equals" + key
+ "please check this then change them");
} else {
String cache_key_real = (String) values[int_value];// 要緩存鍵值的真正cahe值
return cache_key_real;
}
} catch (Exception e) {
log.warn("your filed " + key + " must be String.class");
}
}
return null;
}
/**
* 得到運行時方法對象
*
* @param pjp
* @return
*/
private Method getMethod(ProceedingJoinPoint pjp) {
MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
Method method = methodSignature.getMethod();
return method;
}
}
然後就是xml的配置,注意cglib代理一定要開啓
<bean id="aimpl" class="org.xie.service.Service_A_impl"></bean>
<bean id="bimpl" class="org.xie.service.Service_B_impl"></bean>
<bean id="memDefault" class="org.xie.framework.memcached.spring.MemcachedDefault">
<property name="cached" ref="memClient"></property>
</bean>
<bean id="cacheAop" class="org.xie.framework.memcached.spring.GetCacheAop">
<property name="cacheSupport" ref="memDefault"></property>
</bean>
<aop:aspectj-autoproxy proxy-target-class="true"/> <!-- cglib代理開啓 -->
<aop:config>
<aop:aspect id="myAspect" ref="cacheAop">
<aop:pointcut id="businessService" expression="execution(* org.xie.service.*.*(..))" />
<aop:around pointcut-ref="businessService" method="ProxyInvoke" />
</aop:aspect>
</aop:config>
那麼現在service層的所有方法都有被代理了。那麼我們只需要這樣做,key就表示要緩存的鍵值
@Override
@GetCacheVaule(key="id")//表示要緩存id
public Object testaop(String id) {
return "sssss";
}
其實感覺也沒有什麼好講的,要講的都是在代碼裏面,各位都指點指點吧。但是目前只實現了醉簡單的getcache,以後我會慢慢的完善各種api,敬請期待吧!!
轉載請註明http://blog.csdn.net/a837199685