萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 文件緩存機制 CatchFile 類:頁面級靜態化、過期控制、POST 繞過、目錄自動分月存儲

ASP 頁面級文件緩存組件 CatchFile:從 23 秒優化到 123 毫秒的實戰方案

針對高頻只讀頁面(文章詳情、列表、首頁),將動態生成的 HTML 緩存為靜態文件,後續請求直接讀取文件返回,繞過數據庫查詢與模板渲染。實測 6000 條數據從 23579ms 降至 123ms,提速 190 倍。

使用方式(極簡接入)

<!-- 頁面頂部引入 -->
<!--#include file="FileCatch.asp"-->
<%
Dim MyCatch : Set MyCatch = New CatchFile
MyCatch.Overdue = 10  ' 緩存過期分鐘數,默認 30

If MyCatch.CatchNow(Response) Then
    ' 緩存命中,直接輸出並結束
    Response.Write MyCatch.CatchData
    Response.End
End If

' 緩存未命中或已過期:繼續執行業務邏輯生成頁面
' ... 你的原有代碼 ...
' 頁面末尾無需額外代碼,CatchFile 類析構函數會自動保存緩存
Set MyCatch = Nothing
%>

CatchFile 類完整實現

Class CatchFile
    Public Overdue, Mark, CFolder, CFile, CatchData
    Private ScriptName, ScriptPath, ServerHost
    
    Private Sub Class_Initialize()
        ' 識別當前腳本
        ScriptName = Request.ServerVariables("SCRIPT_NAME")
        ScriptPath = GetFullUrl()  ' 含查詢字符串的完整 URL
        ServerHost = Request.ServerVariables("SERVER_NAME")
        
        ' 默認配置
        Overdue = 30          ' 30 分鐘過期
        Mark = "NoCatch"      ' URL 含此參數強制刷新
        CFolder = GetCacheDir()  ' 自動按 年/月/日 分目錄
        CFile = Server.URLEncode(ScriptPath) & ".txt"
        CatchData = ""
    End Sub
    
    ' 公開方法:檢查緩存是否有效,有效則填充 CatchData 並返回 True
    Public Function CatchNow(ByRef ResponseObj)
        Dim fso, filePath, stream, fileTime
        
        ' 1. POST 請求不緩存
        If UCase(Request.ServerVariables("REQUEST_METHOD")) = "POST" Then Exit Function
        
        ' 2. 強制刷新參數
        If Request.QueryString(Mark) <> "" Then Exit Function
        
        ' 3. 關鍵字過濾(可配置敏感詞不緩存)
        ' If InStr(ScriptPath, "admin") > 0 Then Exit Function
        
        filePath = CFolder & CFile
        Set fso = CreateObject("Scripting.FileSystemObject")
        
        If fso.FileExists(filePath) Then
            ' 4. 檢查過期
            fileTime = fso.GetFile(filePath).DateLastModified
            If DateDiff("n", fileTime, Now()) < Overdue Then
                ' 5. 讀取緩存內容
                Set stream = CreateObject("ADODB.Stream")
                stream.Type = 2 : stream.Mode = 3 : stream.Open
                stream.Charset = "GB2312"  ' 或 UTF-8
                stream.LoadFromFile filePath
                CatchData = stream.ReadText
                stream.Close
                Set stream = Nothing
                Set fso = Nothing
                CatchNow = True
                Exit Function
            End If
        End If
        Set fso = Nothing
        CatchNow = False
    End Function
    
    ' 析構函數:頁面執行結束自動保存緩存
    Private Sub Class_Terminate()
        If CatchData = "" Then Exit Sub  ' 業務邏輯未賦值(如已輸出並 End)
        
        Dim fso, stream
        Set fso = CreateObject("Scripting.FileSystemObject")
        If Not fso.FolderExists(CFolder) Then fso.CreateFolder(CFolder)
        
        Set stream = CreateObject("ADODB.Stream")
        stream.Type = 2 : stream.Mode = 3 : stream.Open
        stream.Charset = "GB2312"
        stream.WriteText CatchData
        stream.SaveToFile CFolder & CFile, 2
        stream.Close
        Set stream = Nothing
        Set fso = Nothing
    End Sub
    
    ' 獲取緩存目錄:/FileCatch/YYYY/MM/DD/
    Private Function GetCacheDir()
        Dim fso, base, y, m, d
        Set fso = CreateObject("Scripting.FileSystemObject")
        base = Server.MapPath("/") & "/FileCatch/"
        If Not fso.FolderExists(base) Then fso.CreateFolder(base)
        
        y = Year(Now())
        m = Right("0" & Month(Now()), 2)
        d = Right("0" & Day(Now()), 2)
        
        base = base & y & "/" & m & "/" & d & "/"
        If Not fso.FolderExists(base) Then fso.CreateFolder(base)
        GetCacheDir = base
        Set fso = Nothing
    End Function
    
    ' 獲取含查詢串的完整 URL
    Private Function GetFullUrl()
        Dim url, qs
        url = "https://" & ServerHost & ScriptName
        qs = Request.ServerVariables("QUERY_STRING")
        If qs <> "" Then url = url & "?" & qs
        GetFullUrl = url
    End Function
End Class

核心設計亮點

特性實現細節
自動保存利用 Class_Terminate 析構函數,頁面正常結束自動寫入緩存,業務代碼零侵入
智能失效POST 請求、強制刷新參數、敏感路徑自動繞過緩存
按天分目錄避免單目錄文件過多導致文件系統性能下降
編碼支持ADODB.Stream 指定 Charset,解決 GB2312/UTF-8 混用亂碼
緩存鍵完整 URL(含查詢串)URLEncode 後作為文件名,天然區分參數

進階優化方向

  • 內存緩存層:熱頁面載入 Application/共享內存,二級緩存再落盤。
  • 依賴驅動失效:數據庫表變更觸發緩存清理(文件系統監聽/DB 觸發器/消息隊列)。
  • 壓縮存儲:GZIP 壓縮 HTML 再存檔,節省 70%+ 磁盤空間與 IO。
  • 分佈式緩存:多服務器場景改用 Redis/Memcached,本地文件緩存不適用。

避坑指南

  1. 緩存內容包含 Session 相關輸出(如用戶名)會導致用戶數據洩露,**緩存頁面必須完全公共化**,用戶態內容用 JS/AJAX 回填。
  2. Response.End 會跳過 Class_Terminate,緩存不會保存。業務代碼中若有 Response.End,需手動調用保存邏輯或重構流程。
  3. 大量小文件導致 inode 耗盡,定期清理過期緩存目錄。

CatchFile 類是 ASP 時代「偽靜態化」的經典實現,思路通用於任何服務端渲染框架。

copyright © 萬盛學電腦網 all rights reserved