public partial class DataListDemo1 : System.Web.UI.Page
{
private SqlConnection conn;
private SqlDataAdapter dad;
private DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
/**使用緩存配置文件以聲明方式設置頁的可緩存性
在應用程序的 Web.config 文件中定義緩存配置文件,在配置文件中包括 duration 和 varyByParam 設置。
下面的 <caching> 配置元素定義名爲 Cache30Seconds 的緩存配置文件,它將在服務器上將頁緩存 30
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="Cache30Seconds" duration="30"
varyByParam="none" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
在使用配置文件的每個 ASP.NET 頁中包含 @ OutputCache 指令,並將 CacheProfile 屬性設置爲 Web.config 文件中定義的緩存配置文件的名稱。
下面的代碼指定頁應當使用名爲 Cache30Seconds 的緩存配置文件:
<%@ OutputCache CacheProfile="Cache30Seconds" %>
**/
/**輸出緩存機制Duration屬性是設置緩存的時間,VaryByParam
* 是否通過參數發生改變
* 聲明式完成
* <%@ OutputCache Duration="10" VaryByParam="none" %>
* 編程式完成
*Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(true);
**/
/** 緩存是由 Cache 類實現的;緩存實例是每個應用程序專用的。
* 緩存生存期依賴於應用程序的生存期;重新啓動應用程序後,將重新創建 Cache 對象。
* Cache 類提供了強大的功能,允許您自定義如何緩存項以及將它們緩存多長時間。
* 例如,當缺乏系統內存時,緩存會自動移除很少使用的或優先級較低的項以釋放內存。
* 該技術也稱爲清理,這是緩存確保過期數據不使用寶貴的服務器資源的方式之一
*
*
*
* 實現數據的緩存機制:先用一個DataSet對象來保存數據緩存的對象,
* 判斷數據緩存的對象是否是空,如果爲空就是用戶第一次請求頁面;
* 就應該從連接數據庫後所得到的表格中獲取數據,而且並且設置給
* 數據緩存對象,如果不是空,就說明是第二次請求頁面,就應該直
* 接獲取已保存在數據緩存中的數據,這樣就可以優化應用程序,不用
* 每次訪問一次頁面要連接一次數據庫取得數據,可以用第一次取得的
* 數據放在數據緩存(對象是存在內存裏的)
* 注意:只對於SqlDataSource控件裏的DataSourceMode屬性是DataSet時,屬性
* 面板上就有設置緩存機制的各種屬性
*
* 通過使用 Insert 方法將項添加到緩存中
* Cache.Insert("MyCache", ds);
* 從緩存中顯式刪除項
* Cache.Remove("MyCache");
*/
//實例化DataSet對象保存Cache對象
ds = (DataSet)Cache["MyCache"];
//判斷數據緩存的對象是否是空
if (ds == null)
{
this.conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["pubsConnectionString"].ToString());
this.dad = new SqlDataAdapter("select emp_id,fname,lname,hire_date from employee", conn);
this.ds = new DataSet();
this.dad.Fill(ds);
//設置DataSet對象保存DataSet對象
Cache["MyCache"] = ds;
this.Label2.Text = "從表格創建的數據";
}
else {
this.Label2.Text = "從緩存獲取的數據";
}
this.DataList1.DataSource = this.ds;
this.DataList1.DataBind();
}