您的位置:首页 > 理论基础 > 计算机网络

DWR框架下修改OSCache的Key以适应域名和IP的两种访问方式

2008-04-24 13:35 344 查看
问题描述

利用OSCache以Filter形式作为缓存以减少服务器压力的时候,客户端对服务器的每次请求不必从服务器调用而后才得到反馈结果,而是从缓存中提取内容返回给客户端即可。在OSCache中提供了一种Key和Value的Map映射,即对每次HTTP请求作为一个Item(可以在把OSCache作为Filter应用的Web工程中的web.xml中配置哪些经过此Filter),将其请求地址和实际内容进行缓存以供将来使用。当第一次进行缓存后,以后每次请求便根据请求的Key从缓存中读取相应的内容了。

当某一应用在实际上线运行时,便提供了域名和IP两种访问方式。当以某一种方式,进行访问的是时候,例如域名访问,OSCache就会把它提供默认的Http请求地址作为Key,即servletPath + pathInfo + queryString,进行缓存。第二次请求开始时候,便根据Key从缓存中查找并返回相应的内容。

而另一方面在利用Ajax框架DWR进行远程调用时候是禁止跨域访问的。而OSCache的这种忽略BashURL(schema + serverName + port + contentPath)提供Key的方式这就造成了Ajax认为出现了跨越访问,从而浏览器报错:XMLHttpRequest禁止跨域访问等错误。其根本原因在于同一个应用有两种访问方式和OSCache的不恰当的Key的提供方式。但在单机测试不提供域名访问的情况下,是很难发现这种错误的。

解决方法

   通过上面的分析,只需要修改OSCache的默认KeyProvider即可,思路很直接:把每次请求的全部地址作为Key即可。具体代码如下:

import javax.servlet.http.HttpServletRequest;




import com.opensymphony.oscache.base.Cache;


import com.opensymphony.oscache.web.ServletCacheAdministrator;


import com.opensymphony.oscache.web.filter.ICacheKeyProvider;






public class URLCacheKeyProvider implements ICacheKeyProvider ...{






    public String createCacheKey(HttpServletRequest httpRequest, ServletCacheAdministrator scAdmin, Cache cache)...{


        String key = getFullURL(httpRequest);


        System.out.println("key = " + key);


        return key;


    }


    




    private String getFullURL(final HttpServletRequest request)...{


        String serverSchema = request.getScheme();


        int serverPort = request.getServerPort();


        


        boolean isDefaultPort = ( (serverSchema.equals("http") 
                               && (serverPort == 80)) 
                               || (serverSchema.equals("https") 
                               && (serverPort == 443)));


        String fullURL = "";


        


        String baseString = serverSchema + "://" 
                        + request.getServerName() 
                        + (isDefaultPort ? "" : (":" + serverPort)) 
                        + request.getContextPath();


        


        fullURL = baseString 
              + request.getServletPath() 
              + request.getPathInfo() 
              + ((request.getQueryString() == null) ? "" : "?" 
              + request.getQueryString());


        


        return fullURL;


    }




}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息