Package com.pccw.hessian.support.cache

Source Code of com.pccw.hessian.support.cache.DefaultCacheHandler$CacheContainner

package com.pccw.hessian.support.cache;

import java.lang.reflect.Method;
import java.util.HashMap;

import com.pccw.hessian.support.cache.CacheHandler;
import com.pccw.hessian.support.cache.CachePolicy;

public class DefaultCacheHandler implements CacheHandler{
 
  private class CacheContainner{
    long brith;
    Object obj;
   
    public CacheContainner(long brith,Object obj) {
      this.brith=brith;
      this.obj=obj;
    }
  }
 
  private HashMap<String,CacheContainner> cache=new HashMap<String, CacheContainner>();
 
  //不需要判断policy为null,policy为null,认定为不适用缓存,不会掉用此方法
  @Override
  public boolean ifReturnFromCahce(Method method, Object[] args) {
    CachePolicy policy=method.getAnnotation(CachePolicy.class);
    if(policy.expires() < 0){
      System.out.println("没有有效期,false");
      return false;
    }
    try {
      String key=getCacheKey(method,args);
      //String key=policy.keyGenerater().newInstance().generatKey(method, args);System.out.println("生成的缓存key:"+key);
      if(cache.containsKey(key)==false){System.out.println("有缓存规则,但缓存中不存在false");
        return false;
      }
      CacheContainner cc=cache.get(key);
      if((System.currentTimeMillis()-cc.brith) < policy.expires()){System.out.println("有缓存规则,且缓存中存在,且没过期true");
        return true;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println("有缓存规则,且缓存中存在,但可能过期,false");
    return false;
  }

  @Override
  public Object returnFromCahce(Method method, Object[] args) {
    try {
      String key=getCacheKey(method,args);
      System.out.println("从缓存中获取");
      CacheContainner cc=cache.get(key);
      return cc==null?null:cc.obj;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  public void onExecuteSuccess(Method method, Object[] args, Object result) {
    try {
      String key=getCacheKey(method,args);
      System.out.println("放入缓存:"+key);
      cache.put(key, new CacheContainner(System.currentTimeMillis(), result));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 
  private String getCacheKey(Method method, Object[] args) throws InstantiationException, IllegalAccessException{
    CachePolicy policy=method.getAnnotation(CachePolicy.class);
    return "".equals(policy.key())?policy.keyGenerater().newInstance().generatKey(method, args):policy.key();
  }

}
TOP

Related Classes of com.pccw.hessian.support.cache.DefaultCacheHandler$CacheContainner

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.