关于高负载高并发的服务器端应用,java解决方案(三)

二,动态缓存

方案1:使用自定义annotation接口进行aspectj动态缓存

 

由于系统需求需要对各个接口进行key-value缓存(以参数为key,返回的对象为value),当然对于这种情况首先考虑到的是使用aop,前段时间看过aspectj的一些介绍,借此机会正好加以应用和体会一下,aspectj是AOP最早成熟的java实现,它稍微扩展了一下java语言,增加了一些keyword等,具体的aspectj的基本语法见这里,进行缓存的框架使用较成熟的ehcache.
下面开始进行配置
首先是ehcache的配置文件

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ehcache>  
  3.     <diskStore path="/home/workspace/gzshine/trunk/ehcache"/>  
  4.     <cache name="DEFAULT_CACHE"  
  5.         maxElementsInMemory="10000"  
  6.         eternal="false"  
  7.         timeToIdleSeconds="3600"  
  8.         timeToLiveSeconds="3600"  
  9.         overflowToDisk="true"  
  10.         />  
  11. </ehcache>   


这个的DEFAULT_CACHE是默认配置,最大的缓存数为10000,时间为一个小时

接下来的是spring下的配置

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xmlns:context="http://www.springframework.org/schema/context"  
  7.     xsi:schemaLocation="  
  8.        http://www.springframework.org/schema/beans  
  9.        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  10.        http://www.springframework.org/schema/tx  
  11.        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd  
  12.        http://www.springframework.org/schema/aop  
  13.        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  14.        http://www.springframework.org/schema/context  
  15.        http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
  16.   
  17. <!-- ##############  aspectj 4 ehcache   ############# -->  
  18.       
  19.     <aop:aspectj-autoproxy proxy-target-class="true"/>  
  20.     <bean id = "methodCacheAspectJ" class="com.***.shine.aspectj.MethodCacheAspectJ" >  
  21.         <property name="cache">  
  22.             <ref local="methodCache" />  
  23.         </property>  
  24.     </bean>  
  25.       
  26.     <bean id="cacheManager"  
  27.         class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
  28.         <property name="configLocation">  
  29.             <value>classpath:ehcache.xml</value>  
  30.         </property>  
  31.     </bean>  
  32.       
  33.     <!-- 定义ehCache的工厂,并设置所使用的Cache name -->  
  34.       
  35.     <bean id="methodCache"  
  36.         class="org.springframework.cache.ehcache.EhCacheFactoryBean">  
  37.         <property name="cacheManager">  
  38.             <ref local="cacheManager" />  
  39.         </property>  
  40.         <property name="cacheName">  
  41.             <value>DEFAULT_CACHE</value>  
  42.         </property>  
  43.     </bean>  



<aop:aspectj-autoproxy proxy-target-class="true"/>
是为aspectj在所有class下开启自动动态代理
<bean id="cacheManager">指定刚刚的ehcache配置文件


接下来编写一个自定义的annotation

Java代码  收藏代码
  1. package com.***.shine.cache;  
  2.   
  3. import java.lang.annotation.Documented;  
  4. import java.lang.annotation.ElementType;  
  5. import java.lang.annotation.Retention;  
  6. import java.lang.annotation.RetentionPolicy;  
  7. import java.lang.annotation.Target;  
  8.   
  9. @Target({ElementType.METHOD,ElementType.TYPE})  
  10. @Retention(RetentionPolicy.RUNTIME)  
  11. @Documented  
  12. public @interface MethodCache {  
  13.     int second() default 0;   
  14. }  



<bean id = "methodCacheAspectJ">是一个aspectj进行Pointcuts和Advice的类需注入methodCache

Java代码  收藏代码
  1. package com.***.shine.aspectj;  
  2.   
  3. @Aspect  
  4. public class MethodCacheAspectJ {  
  5.     Log logger = LogFactory.getLog(MethodCacheAspectJ.class);  
  6.       
  7.     private Cache cache;  
  8.       
  9.     /** 
  10.      * 设置缓存名 
  11.      */  
  12.     public void setCache(Cache cache) {  
  13.         this.cache = cache;  
  14.     }   
  15.       
  16.     @Pointcut("@annotation(com.***.shine.cache.MethodCache)")  
  17.     public void methodCachePointcut(){    
  18.     }  
  19.       
  20.     @Around("methodCachePointcut()")  
  21.     public Object methodCacheHold(ProceedingJoinPoint joinPoint) throws Throwable{  
  22.         String targetName = joinPoint.getTarget().getClass().getName();  
  23.         String methodName = joinPoint.getSignature().getName();  
  24.         Object[] arguments = joinPoint.getArgs();  
  25.         Object result = null;  
  26.         String cacheKey = getCacheKey(targetName, methodName, arguments);  
  27.         Element element = cache.get(cacheKey);  
  28.         if (element == null) {  
  29.             try{  
  30.                 result = joinPoint.proceed();  
  31.             }catch(Exception e){  
  32.                 logger.info(e);  
  33.             }  
  34.             if(result!=null){  
  35.                 try{  
  36.                     element = new Element(cacheKey, (Serializable) result);  
  37.                     Class targetClass = Class.forName(targetName);  
  38.                     Method[] method = targetClass.getMethods();  
  39.                     int second = 0;  
  40.                     for(Method m:method){  
  41.                         if (m.getName().equals(methodName)) {  
  42.                             Class[] tmpCs = m.getParameterTypes();  
  43.                             if(tmpCs.length==arguments.length){  
  44.                                 MethodCache methodCache = m.getAnnotation(MethodCache.class);  
  45.                                 second = methodCache.second();  
  46.                                 break;  
  47.                             }  
  48.                         }  
  49.                     }  
  50.                     if(second>0){ // annotation没有设second值则使用ehcache.xml中自定义值  
  51.                         element.setTimeToIdle(second);  
  52.                         element.setTimeToLive(second);  
  53.                     }  
  54.                     cache.put(element);  
  55.                 }catch(Exception e){  
  56.                     logger.info("!!!!!!!!!"+cacheKey+"!!!!!!!!!未能执行方法缓存"+e);  
  57.                 }  
  58.             }  
  59.         }  
  60.         return element.getValue();  
  61.     }  
  62.   
  63.      private String getCacheKey(String targetName, String methodName,  
  64.             Object[] arguments) {  
  65.         StringBuffer sb = new StringBuffer();  
  66.         sb.append(targetName).append(".").append(methodName);  
  67.         if ((arguments != null) && (arguments.length != 0)) {  
  68.             for (int i = 0; i < arguments.length; i++) {  
  69.                 if (arguments[i] instanceof Date) {  
  70.                     sb.append(".").append(  
  71.                             DateUtil.datetoString((Date) arguments[i]));  
  72.                 } else {  
  73.                     sb.append(".").append(arguments[i]);  
  74.                 }  
  75.             }  
  76.         }  
  77.         return sb.toString();  
  78.     }  
  79. }  



@Pointcut("@annotation(com.netease.shine.cache.MethodCache)")
对有应用com.netease.shine.cache.MethodCache进行注解的方法进行横切面拦截
@Around("methodCachePointcut()")
并在Advice中处理这个Pointcut,这里的的Advice使用的是Around(环绕通知)
String cacheKey = getCacheKey(targetName, methodName, arguments);
接下来使用类型,方法名,参数为key进入缓存处理
Element element = cache.get(cacheKey);
当然如果在cache队列中取得非null对象则直接返回该对象
MethodCache methodCache = m.getAnnotation(MethodCache.class);
second = methodCache.second();
取得second的值(缓存的时间,如在@annotation中无重写只为int second() default 0)
element.setTimeToIdle(second);
element.setTimeToLive(second);
如果非零则重新设置缓存时间

Java代码  收藏代码
  1. @MethodCache(second=300)  
  2. public List<Sort> getSort(int type,int parentid){  
  3.     System.out.println("!!!!!!!!!!!!!没缓存到");  
  4.     Row row = new Row();  
  5.     row.put("type", type);  
  6.     row.put("parentid", parentid);  
  7.     return (List<Sort>)gz_Template.queryForList("sort.getSort", row);  
  8. }  



最后需要将@MethodCache要缓存方法的实现类


方案2 web应用的java动态缓存

 

可以实现不等待,线程自动更新缓存

 

 java动态缓存jar包请下载。

 

源代码:

 

001 CacheData.java 存放缓存数据的Bean
002  
003 /** *//**
004  *
005  */
006 package com.cari.web.cache;
007  
008 /** *//**
009  * @author zsy
010  *
011  */
012 public class CacheData {
013     private Object data;
014     private long time;
015     private int count;
016      
017     public CacheData() {
018          
019     }
020      
021     public CacheData(Object data, long time, int count) {
022         this.data = data;
023         this.time = time;
024         this.count = count;
025     }
026      
027     public CacheData(Object data) {
028         this.data = data;
029         this.time = System.currentTimeMillis();
030         this.count = 1;
031     }
032      
033     public void addCount() {
034         count++;
035     }
036      
037     public int getCount() {
038         return count;
039     }
040     public void setCount(int count) {
041         this.count = count;
042     }
043     public Object getData() {
044         return data;
045     }
046     public void setData(Object data) {
047         this.data = data;
048     }
049     public long getTime() {
050         return time;
051     }
052     public void setTime(long time) {
053         this.time = time;
054     }
055 }
056  
057  
058  
059 CacheOperation.java 缓存处理类
060  
061 package com.cari.web.cache;
062  
063 import java.lang.reflect.Method;
064 import java.util.ArrayList;
065 import java.util.Arrays;
066 import java.util.Hashtable;
067  
068 import org.apache.commons.logging.Log;
069 import org.apache.commons.logging.LogFactory;
070  
071 /** *//**
072  * @author zsy
073  */
074 public class CacheOperation {
075     private static final Log log = LogFactory.getLog(CacheOperation.class);
076     private static CacheOperation singleton = null;
077      
078     private Hashtable cacheMap;//存放缓存数据
079      
080     private ArrayList threadKeys;//处于线程更新中的key值列表
081      
082     public static CacheOperation getInstance() {
083         if (singleton == null) {
084             singleton = new CacheOperation();
085         }
086         return singleton;
087     }
088      
089     private CacheOperation() {
090         cacheMap = new Hashtable();
091         threadKeys = new ArrayList();
092     }
093      
094     /** *//**
095      * 添加数据缓存
096      * 与方法getCacheData(String key, long intervalTime, int maxVisitCount)配合使用
097      * @param key
098      * @param data
099      */
100     public void addCacheData(String key, Object data) {
101         addCacheData(key, data, true);
102     }
103      
104     private void addCacheData(String key, Object data, boolean check) {
105         if (Runtime.getRuntime().freeMemory() < 5L*1024L*1024L) {//虚拟机内存小于10兆,则清除缓存
106             log.warn("WEB缓存:内存不足,开始清空缓存!");
107             removeAllCacheData();
108             return;
109         else if(check && cacheMap.containsKey(key)) {
110             log.warn("WEB缓存:key值= " + key + " 在缓存中重复, 本次不缓存!");
111             return;
112         }
113         cacheMap.put(key, new CacheData(data));
114     }
115      
116     /** *//**
117      * 取得缓存中的数据
118      * 与方法addCacheData(String key, Object data)配合使用
119      * @param key
120      * @param intervalTime 缓存的时间周期,小于等于0时不限制
121      * @param maxVisitCount 访问累积次数,小于等于0时不限制
122      * @return
123      */
124     public Object getCacheData(String key, long intervalTime, int maxVisitCount) {
125         CacheData cacheData = (CacheData)cacheMap.get(key);
126         if (cacheData == null) {
127             return null;
128         }
129         if (intervalTime > 0 && (System.currentTimeMillis() - cacheData.getTime()) > intervalTime) {
130             removeCacheData(key);
131             return null;
132         }
133         if (maxVisitCount > 0 && (maxVisitCount - cacheData.getCount()) <= 0) {
134             removeCacheData(key);
135             return null;
136         else {
137             cacheData.addCount();
138         }
139         return cacheData.getData();
140     }
141      
142     /** *//**
143      * 当缓存中数据失效时,用不给定的方法线程更新数据
144      * @param o 取得数据的对像(该方法是静态方法是不用实例,则传Class实列)
145      * @param methodName 该对像中的方法
146      * @param parameters 该方法的参数列表(参数列表中对像都要实现toString方法,若列表中某一参数为空则传它所属类的Class)
147      * @param intervalTime 缓存的时间周期,小于等于0时不限制
148      * @param maxVisitCount 访问累积次数,小于等于0时不限制
149      * @return
150      */
151     public Object getCacheData(Object o, String methodName,Object[] parameters,
152             long intervalTime, int maxVisitCount) {
153         Class oc = o instanceof Class ? (Class)o : o.getClass();
154         StringBuffer key = new StringBuffer(oc.getName());//生成缓存key值
155         key.append("-").append(methodName);
156         if (parameters != null) {
157             for (int i = 0; i < parameters.length; i++) {
158                 if (parameters[i] instanceof Object[]) {
159                     key.append("-").append(Arrays.toString((Object[])parameters[i]));
160                 else {
161                     key.append("-").append(parameters[i]);
162                 }
163             }
164         }
165          
166         CacheData cacheData = (CacheData)cacheMap.get(key.toString());
167         if (cacheData == null) {//等待加载并返回
168             Object returnValue = invoke(o, methodName, parameters, key.toString());
169             return returnValue instanceof Class ? null : returnValue;
170         }
171         if (intervalTime > 0 && (System.currentTimeMillis() - cacheData.getTime()) > intervalTime) {
172             daemonInvoke(o, methodName, parameters, key.toString());//缓存时间超时,启动线程更新数据
173         else if (maxVisitCount > 0 && (maxVisitCount - cacheData.getCount()) <= 0) {//访问次数超出,启动线程更新数据
174             daemonInvoke(o, methodName, parameters, key.toString());
175         else {
176             cacheData.addCount();
177         }
178         return cacheData.getData();
179     }
180          /** *//**
181      * 递归调用给定方法更新缓存中数据据
182      * @param o
183      * @param methodName
184      * @param parameters
185      * @param key
186      * @return 若反射调用方法返回值为空则返回该值的类型
187      */
188     private Object invoke(Object o, String methodName,Object[] parameters, String key) {
189         Object returnValue = null;
190         try {
191            Class[] pcs = null;
192             if (parameters != null) {
193                 pcs = new Class[parameters.length];
194                 for (int i = 0; i < parameters.length; i++) {
195                     if (parameters[i] instanceof MethodInfo) {//参数类型是MethodInfo则调用该方法的返回值做这参数
196                         MethodInfo pmi = (MethodInfo)parameters[i];
197                         Object pre = invoke(pmi.getO(), pmi.getMethodName(), pmi.getParameters(), null);
198                         parameters[i] = pre;
199                     }
200                     if (parameters[i] instanceof Class) {
201                         pcs[i] = (Class)parameters[i];
202                         parameters[i] = null;
203                     else {
204                         pcs[i] = parameters[i].getClass();
205                     }
206                 }
207             }
208             Class oc = o instanceof Class ? (Class)o : o.getClass();
209         //    Method m = oc.getDeclaredMethod(methodName, pcs);
210             Method m = matchMethod(oc, methodName, pcs);
211             returnValue = m.invoke(o, parameters);
212             if (key != null && returnValue != null) {
213                 addCacheData(key, returnValue, false);
214             }
215             if (returnValue == null) {
216                 returnValue = m.getReturnType();
217             }
218         catch(Exception e) {
219             log.error("调用方法失败,methodName=" + methodName);
220             if (key != null) {
221                 removeCacheData(key);
222                 log.error("更新缓存失败,缓存key=" + key);
223             }
224             e.printStackTrace();
225         }
226         return returnValue;
227     }
228      
229     /** *//**
230      * 找不到完全匹配的方法时,对参数进行向父类匹配
231      * 因为方法aa(java.util.List) 与 aa(java.util.ArrayList)不能自动匹配到
232      *
233      * @param oc
234      * @param methodName
235      * @param pcs
236      * @return
237      * @throws NoSuchMethodException
238      * @throws NoSuchMethodException
239      */
240     private Method matchMethod(Class oc, String methodName, Class[] pcs
241             throws NoSuchMethodException, SecurityException {
242         try {
243             Method method = oc.getDeclaredMethod(methodName, pcs);
244             return method;
245         catch (NoSuchMethodException e) {
246             Method[] ms = oc.getDeclaredMethods();
247             aa:for (int i = 0; i < ms.length; i++) {
248                 if (ms[i].getName().equals(methodName)) {
249                     Class[] pts = ms[i].getParameterTypes();
250                     if (pts.length == pcs.length) {
251                         for (int j = 0; j < pts.length; j++) {
252                             if (!pts[j].isAssignableFrom(pcs[j])) {
253                                 break aa;
254                             }
255                         }
256                         return ms[i];
257                     }
258                 }
259             }
260             throw new NoSuchMethodException();
261         }
262     }
263      
264     /** *//**
265      * 新启线程后台调用给定方法更新缓存中数据据
266      * @param o
267      * @param methodName
268      * @param parameters
269      * @param key
270      */
271     private void daemonInvoke(Object o, String methodName,Object[] parameters, String key) {
272         if (!threadKeys.contains(key)) {
273             InvokeThread t = new InvokeThread(o, methodName, parameters, key);
274             t.start();
275         }
276     }
277      
278     /** *//**
279      * 些类存放方法的主调对像,名称及参数数组
280      * @author zsy
281      *
282      */
283     public class MethodInfo {
284         private Object o;
285         private String methodName;
286         private Object[] parameters;
287         public MethodInfo(Object o, String methodName,Object[] parameters) {
288             this.o = o;
289             this.methodName = methodName;
290             this.parameters = parameters;
291         }
292         public String getMethodName() {
293             return methodName;
294         }
295         public void setMethodName(String methodName) {
296             this.methodName = methodName;
297         }
298         public Object getO() {
299             return o;
300         }
301         public void setO(Object o) {
302             this.o = o;
303         }
304         public Object[] getParameters() {
305             return parameters;
306         }
307         public void setParameters(Object[] parameters) {
308             this.parameters = parameters;
309         }
310          
311         public String toString() {
312             StringBuffer str = new StringBuffer(methodName);
313             if (parameters != null) {
314                 str.append("(");
315                 for (int i = 0; i < parameters.length; i++) {
316                     if (parameters[i] instanceof Object[]) {
317                         str.append(Arrays.toString((Object[])parameters[i])).append(",");
318                     else {
319                         str.append(parameters[i]).append(",");
320                     }
321                 }
322                 str.append(")");
323             }
324             return str.toString();
325         }
326     }
327      
328     /** *//**
329      * 线程调用方法
330      * @author zsy
331      *
332      */
333     private class InvokeThread extends Thread {
334         private Object o;
335         private String methodName;
336         private Object[] parameters;
337         private String key;
338         public InvokeThread(Object o, String methodName,Object[] parameters, String key) {
339             this.o = o;
340             this.methodName = methodName;
341             this.parameters = parameters;
342             this.key = key;
343         }
344          
345         public void run() {
346             threadKeys.add(key);
347             invoke(o, methodName, parameters, key);
348             threadKeys.remove(key);
349         }
350     }
351      
352     /** *//**
353      * 移除缓存中的数据
354      * @param key
355      */
356     public void removeCacheData(String key) {
357         cacheMap.remove(key);
358     }
359      
360     /** *//**
361      * 移除所有缓存中的数据
362      *
363      */
364     public void removeAllCacheData() {
365         cacheMap.clear();
366     }
367      
368     public String toString() {
369         StringBuffer sb = new StringBuffer("************************ ");
370         sb.append("正在更新的缓存数据: ");
371         for (int i = 0; i < threadKeys.size(); i++) {
372             sb.append(threadKeys.get(i)).append(" ");
373         }
374         sb.append("当前缓存大小:").append(cacheMap.size()).append(" ");
375         sb.append("************************");
376         return sb.toString();
377     }
378

}

 

 

用法:

例1:代码片段如下:

01 public class Test {
02  
03   String rulStr=.;
04  
05   String encoding=.;
06  
07   public void getData() {
08  
09     DataCreator c = new DataCreator();
10  
11     String result = c.initUrlData(urlStr,encoding);
12  
13     System.out.println(result);
14  
15   }
16  
17 }

 

 

每次执行上面代码时都要通过调用 initUrlData方法取得数据,假设此方法很耗资源而耗时间,但对数据时实性要求不高,就是可以用以下方式进行缓存处理,保证很快地取得数据,并根据设置的参数自动更新缓存中数据

注意:initUrlData方法参数值一样时才属于同一个缓存,否则会生成一个新的缓存,也就是说从缓存中取数据与initUrlData方法参数值有关

 

01 public void getData() {
02  
03     DataCreator data = new DataCreator();
04  
05     CacheOperation co = CacheOperation.getInstance();
06  
07     String str = (String)co.getCacheData(data, "initUrlData",new Object[]{urlStr, encoding},  120000100);
08  
09     System.out.println(result);
10  
11   }

 

 

getCacheData方法返回值与initUrlData方法返回类型一样,参数说明:

data:调用initUrlData方法的实列,如果该方法是静态的,则传类的类型,如(DataCreator .class);

"initUrlData":方法名称;

new Object[]{urlStr, encoding}:initUrlData方法的参数数组,如果某一参数为空则传该参数的类型,若encoding 为空,则为new Object[]{urlStr, String.class}或new Object[]{urlStr, ""};

120000:缓存时间,单位:豪秒,即过两分钟更新一次缓存;值为0时为不限,即不更新缓存;

100:访问次数,当缓存中数据被访问100次时更新一次缓存;值为0时为不限,即不更新缓存;

例2:代码片段如下:

 

1 String province = request.getParameter("province");
2  
3 String city= request.getParameter("city");
4  
5 String county= request.getParameter("county");
6  
7 Document doc = XMLBuilder.buildLatelyKeyword(kwm.latelyKeyword(province, city, county));
8  
9 out.write(doc);

 

 

 

做缓存并两分钟更新一次,如下:

 

01 String province = request.getParameter("province");
02  
03 String city= request.getParameter("city");
04  
05 String county= request.getParameter("county");
06  
07 CacheOperation co = CacheOperation.getInstance();
08  
09 MethodInfo mi = co.new MethodInfo(kwm, "latelyKeyword"new Object[]{province, city, county});
10    
11 Document doc = (Document )co.getCacheData(XMLBuilder.class,"buildLatelyKeyword",new Object[],1200000);
12  
13 out.write(doc);

 

 

 

以上方法是嵌套调用, 要先定义内部方法说明即MethodInfo,此类是CacheOperation 的一个内部类。

posted on 2011-10-09 10:41  苏桓(osbert)  阅读(593)  评论(0编辑  收藏  举报

导航