欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

在JScript中使用缓存技术的实际代码

程序员文章站 2022-08-06 10:35:03
在使用vbscript时,我们可以用application缓存数组来实现缓存,例: 程序代码: 复制代码 代码如下:dim rs,arr  rs.ope...
在使用vbscript时,我们可以用application缓存数组来实现缓存,例:

程序代码:
复制代码 代码如下:

dim rs,arr 
rs.open conn,sql,1,1 
arr=rs.getrows() 
application.lock() 
application("cache")=arr 
applicatoin.unlock() 

在vbscript里,数组是可以存到application对象里的,但是如果asp的语言选择为jscript的话,那么就有些不妙了,我们在使用application储存一个数组时,会出现以下错误:

引用内容:
application object, asp 0197 (0x80004005)

disallowed object use

cannot add object with apartment model behavior to the application intrinsic object.

在微软的知识库可以找到具体原因如下:

引用内容:
jscript arrays are considered to be "apartment" com components. only component object model (com) components that aggregate the free threaded marshaler (ftm) can be assigned to application scope within an internet information server (iis) 5.0 asp page. because an "apartment" component cannot aggregate the ftm (it cannot allow a direct pointer to be passed to its clients, unlike a "both with ftm" object), jscript arrays do not aggregate the ftm. therefore, jscript arrays cannot be assigned to application scope from an asp page.

以上描述引用自:prb: error when you store a jscript array in application scope in iis 5.0

因此,为了解决这个问题,在google里找了一大会,终于找到了一篇文章《application对象的contents和staticobjects做cache的一些结论》,解决了这个问题,方法就是使用application.staticobject存放一个scripting.dictionary对象,然后再使用scripting.dictionary对象来存放需要缓存的数据。

据此,写了一个操作缓存的类,实现put、get、remove和clear方法,使用之前,需要在global.asa中添加一个object:

程序代码:
<object id="xbscache" runat="server" scope="application" progid="scripting.dictionary"></object>
类的实现如下:
复制代码 代码如下:

<script language="jscript" runat="server"> 
/** 
 title: cache operate class 
 description: operate system cache 
 @copyright: copyright (c) 2007 
 @author: xujiwei 
 @website: http://www.xujiwei.cn/ 
 @version: 1.0 
 @time: 2007-06-29 12:03:45 
**/ 
var xbscache = { 
    get: function(key) { 
        return application.staticobjects("xbscache").item("cache."+key); 
    }, 
    put: function(key, data) { 
        application.lock(); 
        application.staticobjects("xbscache").item("cache."+key)=data; 
        application.unlock(); 
    }, 
    remove: function(key) { 
        application.lock(); 
        application.staticobjects("xbscache").remove("cache."+key); 
        application.unlock(); 
    }, 
    clear: function() { 
        application.lock(); 
        application.staticobjects("xbscache").removeall(); 
        application.unlock(); 
    } 

</script> 
如此,就完成了asp中使用jscript时的缓存实现。