首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

ASP.NET Cache 快取失效的三種核心策略實作

     編輯:關於C語言

快取失效機制概述

在 Web 應用中,Cache 物件允許將資料保存在記憶體中,避免重複查詢資料庫。設定合理的失效策略至關重要,本文示範三種常見方式:檔案相依性、絕對過期時間、滑動過期時間。

前端頁面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CacheDemo.WebForm1" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Cache 失效策略示範</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server"></asp:GridView>
        </div>
    </form>
</body>
</html>

後端程式碼

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Cache["news"] == null)
        {
            DataTable dt = LoadData();

            // 策略一:檔案相依性 —— 檔案異動即刻失效
            // Cache.Insert("news", dt, new CacheDependency(@"d:\cache.txt"));

            // 策略二:絕對過期時間 —— 固定時間點失效
            // Cache.Insert("news", dt, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero);

            // 策略三:滑動過期時間 —— 閒置超過指定時間失效(此處啟用)
            Cache.Insert("news", dt, null, DateTime.MaxValue, TimeSpan.FromSeconds(30));

            // 簡單快取(無失效策略,需手動移除)
            // Cache.Insert("news", dt);

            this.GridView1.DataSource = dt;
            this.GridView1.DataBind();
        }
        else
        {
            DataTable dt = Cache["news"] as DataTable;
            this.GridView1.DataSource = dt;
            this.GridView1.DataBind();
        }
    }
}

private DataTable LoadData()
{
    string strcon = ConfigurationManager.ConnectionStrings["Sqlserver"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(strcon))
    using (SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = "pro_FenYe";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@pagesize", 500);
        cmd.Parameters.AddWithValue("@pageindex", 1);
        DataTable dt = new DataTable();
        using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
        {
            adapter.Fill(dt);
        }
        return dt;
    }
}

三種策略對比

策略適用場景特點
檔案相依性設定檔、外部資料檔變更需即時反映檔案異動即觸發失效,即時性強
絕對過期資料更新頻率固定、可預測的業務到點必失效,簡單可控
滑動過期熱門資料、讀取頻率不固定持續被存取則延長壽命,節省記憶體

Web.config 中的 SQL 快取相依性設定

<system.web>
    <compilation debug="true" targetFramework="4.0" />
    <caching>
        <sqlCacheDependency pollTime="500">
            <databases>
                <add name="sqldependency" connectionStringName="Sqlserver" />
            </databases>
        </sqlCacheDependency>
    </caching>
</system.web>

pollTime 為輪詢間隔(毫秒),需搭配 aspnet_regsql 啟用資料庫查詢通知。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved