天天看點

ASP.NET網站開發——資料緩存技術資料緩存技術

資料緩存技術

緩存概念:緩存是一種在計算機中廣泛用來提高性能的技術。在web應用程式的上下文中,緩存用于在Http請求間保留頁或者資料,并在無需多建立的情況下多次使用它們。

目的:節省應用程式處理時間和資源

緩存體系:

ASP.NET網站開發——資料緩存技術資料緩存技術

@outputcache指令

ASP.NET網站開發——資料緩存技術資料緩存技術

Httpcachepolicy類

protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = DateTime.Now.ToLongTimeString();
        }
        public static string GetTime(HttpContext conten) 
        {
            return DateTime.Now.ToLongTimeString();
        }
           

頁面部分緩存

把@outputcache指令寫入使用者控件檔案中

ASP.NET網站開發——資料緩存技術資料緩存技術

substitution控件

在使用substitution時,首先我們将整個頁面緩存起來,然後将頁面中需要動态改變内容的地方用substitution控件代替即可。substitution控件需要設定一個重要屬性methodname,該屬性用于擷取或者設定當substitution控件執行時為回調而調用的方法名稱。

回調方法必須要符合三點:

(1)回調方法必須定義為靜态方法。

(2)方法必須接受httpcontext類型的參數。

(3)方法必須傳回string類型的值。

緩存後替存

ASP.NET網站開發——資料緩存技術資料緩存技術

應用程式資料緩存

應用程式資料緩存的主要功能是在記憶體中存儲各種與應用程式相關的對象,通常這些能量都需要耗費大量的伺服器資源才能建立,應用程式資料緩存由cache實作。

ASP.NET網站開發——資料緩存技術資料緩存技術
ASP.NET網站開發——資料緩存技術資料緩存技術

下面是add方法

protected void btnadd_Click(object sender, EventArgs e)
        {
            try
            {
                Cache.Add("aaa","ADD CACHE",null,Cache.NoAbsoluteExpiration,Cache.NoSlidingExpiration,CacheItemPriority.Default,null);

            }
            catch
            {
                Response.Write("ERROR");
                
            }
        }
           

下面是insert方法

protected void btninsert_Click(object sender, EventArgs e)
        {
            Cache.Insert("aaa","INSERT CACHE");
        }
           

下面是擷取get方法

protected void btnget_Click(object sender, EventArgs e)
        {
            //get
            Cache.Get("");

            //索引
            if (Cache["aaa"]!=null)
            {
                string str = (string)Cache["aaa"];
                Response.Write(str);
            }
            else
            {
                Response.Write("緩存無效!");
            }
        }
           

下面是網頁效果

ASP.NET網站開發——資料緩存技術資料緩存技術
ASP.NET網站開發——資料緩存技術資料緩存技術

繼續閱讀