您所在的位置:小祥子 » 编程 » ASP » 正文

ASP缓存类缓存方法

时间:2015-03-03 编辑:本站 来源:本站原创

<%
'当前URL
Function GetThisUrl()
 Dim StrUrl
 Dim StrParam
 StrUrl     = Request.ServerVariables("URL")
If Trim(Request.QueryString) <> "" Then
 StrParam  = "?" & Trim(Request.QueryString)
Else
 StrParam  = ""
End If
GetThisUrl = StrUrl & StrParam
End Function

'获取原有页面代码
Function getpagecontent(url)
Dim http
Set http = Server.CreateObject("Microsoft.XMLHTTP")
With Http
 .open "GET",url,False
 .send()
 If .readystate <> 4 Then
  Exit Function
 End If
 getpagecontent = B2Bstr(.responseBody,"GB2312")
End With
Set http        = Nothing
If Err.Number <> 0 Then Err.Clear
End Function

'转换编码
Function B2Bstr(body,Cset)
Dim obJStream
Set objstream = Server.CreateObject("adodb.stream")
With objstream
 .Type        = 1
 .Mode        = 3
 .Open
 .Write body
 .Position = 0
 .Type     = 2
 .Charset  = Cset
 B2Bstr    = .ReadText
 .Close
End With
Set objstream = Nothing
End Function

'创建缓存
Sub CreateCacheFile(Filename,temp)
 Set fso = CreateObject("Scripting.FileSystemObject")
 Set tf  = fso.CreateTextFile(Filename, True)
 tf.Write temp
 tf.Close
End Sub

'读取缓存
Function ReadCacheFile(TempString)
Dim str
Set stm   = Server.CreateObject("adodb.stream")
With stm
 .Type    = 2
 .Mode    = 3
 .Charset = "gb2312"
 .Open
 .loadfromfile TempString
 str = .readtext
 .Close
End With
Set stm       = Nothing
ReadCacheFile = str
End Function

Dim thisurl,thisdomain,cachefile
thisurl  = GetThisUrl()
thisdomain=Request.ServerVariables("SERVER_NAME")
If InStr(thisurl,"?") > 0 Then
cacheurl = "http://" & thisdomain & thisurl & "&iscache=1"
Else
cacheurl = "http://" & thisdomain & thisurl & "?iscache=1"
End If
cachefile = Server.MapPath("/cache/" & Server.URLEncode(thisurl) & ".cache")

If Not Int(Request.QueryString("iscache")) = 1 Then
 Set fs    = Server.CreateObject("Scripting.FileSystemObject")
 If fs.FileExists(cachefile) Then   '查询缓存是否存在
 '存在应该继续判断缓存最后修改时间
  If DateDiff("s",fs.GetFile(cachefile).DateLastModified,Now()) < 1800 Then
   Response.Write ReadCacheFile(cachefile)
   Set fs = Nothing
   response.End()
  Else
   Call CreateCacheFile(cachefile,getpagecontent(cacheurl))
   Response.Write ReadCacheFile(cachefile)
   Set fs = Nothing
   response.End()
  End If
 Else
  '缓存后立即读取缓存文件
  Call CreateCacheFile(cachefile,getpagecontent(cacheurl))
  Response.Write ReadCacheFile(cachefile)
  Set fs = Nothing
  response.End()
 End If
End If
%>

使用方法 首先手动建立一个cache目录,然后再需要被缓存的目录加以下代码

<!--#include file="cache.ASP"-->
这里是一长串需要查询数据库的代码

关键词:ASP 缓存 方法