一个利用ehcache和AOP做的缓存切面类。

缓存操作类。
package cache;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class OACache {

private static Log logger = LogFactory.getLog(OACache.class);

private static Map<String,Cache> cacheMap=new ConcurrentHashMap<String,Cache>();

static{
CacheManager.create();
}

/**
* 取得cache
* @param cacheName
* @return
*/
public synchronized static Cache getCache(String cacheName){

Cache cache=cacheMap.get(cacheName);

if(cache!=null){
logger.debug("return");
return cache;
}
else
{
logger.debug("create");
cache = CacheManager.getInstance().getCache(cacheName);
cacheMap.put(cacheName,cache);
return cache;
}
}

/**
* 向cache中输入值
* @param cacheName
* @param id
* @param obj
*/
public synchronized static void putObject(String cacheName,String id,Object obj){
Element element=new Element(id,obj);

getCache(cacheName).put(element);
}

/**
* 从cache中取值。
* @param cacheName
* @param id
* @return
*/
public synchronized static Object getObject(String cacheName,String id){
Cache cache=getCache(cacheName);

try{
    return cache.get(id).getObjectValue();
}catch(NullPointerException e){
return null;
}
}

/**
* 从cache中删除值。
* @param cacheName
* @param id
* @return
*/
public synchronized static void removeObject(String cacheName,String id){
Cache cache=getCache(cacheName);

cache.remove(id);
}

/**
* 清除所有的缓存。
*/
public synchronized static void shutDownAllCache(){
CacheManager.getInstance().shutdown();
}

}
缓存切面类
package advice;

import java.util.List;
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 util.string.StringUtil;
import cache.OACache;

public class CacheAdvice {

private static Log logger = LogFactory.getLog(CacheAdvice.class);

private List<String> cacheMethodList;
private Map<String,String> updateMethodList;

private String cacheName;

/**
* cache的名称,根据ehcache设置。
* @param cacheName
*/
public void setCacheName(String cacheName) {
this.cacheName = cacheName;
}
/**
* 需要缓存的方法名,
* @param cacheMethodList
*/
public void setCacheMethodList(List<String> cacheMethodList) {
this.cacheMethodList = cacheMethodList;
}
/**
* 当执行这些方法时,需要更新缓存。
* @param updateMethodList
*/
public void setUpdateMethodList(Map<String, String> updateMethodList) {
this.updateMethodList = updateMethodList;
}

/**
* 缓存。
* @param point
* @return
* @throws Throwable
*/
public Object cache(ProceedingJoinPoint point) throws Throwable{ 

//注意监视的对象如果有返回值本方法也要有返回值

String methodName  = point.getSignature().getName();
String targetName  = point.getTarget().getClass().getName();
    Object[] arguments = point.getArgs();
    Object result;
   
   
     if(needToUpdate(methodName)){
   
        String[] updateMethodArray=updateMethodList.get(methodName).split(",");
       
        for(String method:updateMethodArray){
       
          logger.debug("remove "+method.trim()+" from  cache!!");
         
      OACache.removeObject(cacheName,method.trim());      
        }
       
        return point.proceed();
          }
           else if(!needToCache(methodName))
           {
       
    logger.debug(targetName+"-"+methodName+" need not to cache!!");
   
    return point.proceed();
   
        }
           else
           {
           String cacheKey=getCacheKey(targetName,methodName,arguments);
          
           Map<String,Object> mapResult=(Map<String,Object>)OACache.getObject(cacheName,methodName);
          
           if(mapResult!=null){
          
           if(mapResult.get(cacheKey)!=null){
           logger.debug(cacheKey+" has already cached,load from cache!!");
          
           return mapResult.get(cacheKey);
           }
           else
           {
           result=point.proceed();
           mapResult.put(cacheKey,result);
          
           OACache.putObject(cacheName,methodName,mapResult);
           logger.debug("use old map and "+cacheKey+" caching!!");
          
           return result;
           }
           }
           else
           {
                       result=point.proceed();
          
           mapResult=new ConcurrentHashMap();
          
           mapResult.put(cacheKey,result);           
           OACache.putObject(cacheName,methodName,mapResult);
          
           logger.debug("make new map and "+cacheKey+" caching!!");
          
           return result;
           }
          
           }
   
}

/**
* 根据执行的类,方法名和参数返回cachekey。
* @param targetName
* @param methodName
* @param arguments
* @return
*/
private String getCacheKey(String targetName,String methodName,Object[] arguments) {
StringBuffer sb = new StringBuffer();

sb.append(targetName).append(".").append(methodName);

if ((arguments != null) && (arguments.length != 0)) {
for (int i=0; i<arguments.length; i++) {
sb.append(".").append(arguments[i]);
}
}

return sb.toString();
    }

/**
* 检测是否需要更新。
* @param methodName
* @return
*/
private boolean needToUpdate(String methodName){

if(updateMethodList.get(methodName)==null)
  {
return false;
  }
  else
  {
return true;
  }
}

/**
* 检测是否需要缓存。
* @param methodName
* @return
*/
private boolean needToCache(String methodName){
return StringUtil.inStr(methodName,cacheMethodList.toArray(new String[0]));
}

}
切面在spring中的设置。
<bean id="cacheAdvice" class="advice.CacheAdvice" scope="singleton" >

  <property name="cacheMethodList">
        <list>
          <value>findMessageReceiveByMessageTypeAndStaffid</value>
          <value>getCountBulletinReceiveByDeptid</value>
          <value>findBulletinReceiveByDeptid</value>
          <value>getCountMessageReceiveByMessageTypeAndStaffid</value>         
          <value>findNewMessageByStaffid</value>
          <value>getCountNewMessageByStaffid</value>
          <value>getCountMessageSentByTypeAndStaffid</value>
          <value>findMessageSentByMessageTypeAndStaffid</value>
        </list>
      </property>
     
      <property name="updateMethodList">
        <map>
          <entry key="saveMessage">
            <value>
            findMessageSentByMessageTypeAndStaffid,
            getCountMessageSentByTypeAndStaffid,
            findMessageReceiveByMessageTypeAndStaffid,
            getCountMessageReceiveByMessageTypeAndStaffid,
            findNewMessageByStaffid,
            getCountNewMessageByStaffid
            </value>
          </entry>
          <entry key="senderDel">
            <value>
            findMessageSentByMessageTypeAndStaffid,
            getCountMessageSentByTypeAndStaffid,
            findMessageReceiveByMessageTypeAndStaffid,
            getCountMessageReceiveByMessageTypeAndStaffid,
            findNewMessageByStaffid,
            getCountNewMessageByStaffid
            </value>
          </entry>
          <entry key="receiverDel">
            <value>
            findMessageSentByMessageTypeAndStaffid,
            getCountMessageSentByTypeAndStaffid,
            findMessageReceiveByMessageTypeAndStaffid,
            getCountMessageReceiveByMessageTypeAndStaffid,
            findNewMessageByStaffid,
            getCountNewMessageByStaffid
            </value>
          </entry>
        </map>
      </property>
     
      <property name="cacheName">
        <value>pagecache</value>
      </property>
     
    </bean>

你可能感兴趣的:(apache,AOP,.net,cache)