很多時候,我們服務器的性能瓶頸會是在查詢數據庫的時候,所以對數據庫的緩存非常重要,那麼有沒有一種方法,可以實現SQL Server數據庫的緩存,當數據表沒有更新時,就從緩存中讀取,當有更新的時候,才從數據表中讀取呢,答案是肯定的,這樣的話我們對一些常用的基礎數據表就可以緩存起來,比如做新聞系統的新聞類別等,每次就不需要從數據庫中讀取了,加快網站的訪問速度。
那麼如何開啟SQLSERVER數據庫緩存依賴,方法如下:
第一步:修改Web.Config的<system.web>節的配置,代碼如下,讓網站項目啟用SqlCacheDependency。注意下面代碼中的connectionStringName,就是指定的<connectionStrings>節中的數據庫連接字符串變量名稱。name則是為該SqlCacheDependency起的名字,這個名字將在第三步中用到。SqlCacheDependency類會自動完成對此配置節信息的讀取以建立和數據庫之間的聯系。
vIEw plaincopy to clipboardprint?
<system.web>
<httpHandlers>
<add verb="*" path="*.ASPx"
type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
<add verb="*" path="*.sHtml"
type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
<add verb="*" path="*.bobo"
type="URLRewriter.RewriterFactoryHandler, URLRewriter" /> </httpHandlers>
<!-->以下設置數據庫緩存依賴方式-->
<caching>
<sqlCacheDependency enabled="true" pollTime="6000">
<databases>
<add name="YD_JWC_JAKE" connectionStringName="cachestr"/>
</databases>
</sqlCacheDependency>
</caching>
<!--
設置 compilation debug="true" 將調試符號插入 影響性能,因此只在開發過程中將此值
設置為 true。
-->
<compilation debug="true">
<assemblIEs>
<add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
</assemblIEs>
</compilation>
<!--
通過 <authentication> 節可以配置 ASP.Net 使用的 以標識傳入的用戶。
-->
<authentication mode="Forms">
<forms loginUrl="login.ASPx" name=".AJSUPCXAIUTH"></forms>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
<!-- 則通過 <customErrors> 節可以配置相應的處理步驟。具體說來, 要顯示的 Html 錯誤頁
以代替錯誤堆棧跟蹤。-->
<customErrors mode="RemoteOnly" defaultRedirect="/ER3.sHtml">
<error statusCode="403" redirect="/ER1.sHtml" />
<error statusCode="404" redirect="/ER404.sHtml" />
</customErrors>
</system.web>
<system.web>
<httpHandlers>
<add verb="*" path="*.ASPx"
type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
<add verb="*" path="*.sHtml"
type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
<add verb="*" path="*.bobo"
type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
</httpHandlers>
<!-->以下設置數據庫緩存依賴方式-->
<caching>
<sqlCacheDependency enabled="true" pollTime="6000">
<databases>
<add name="YD_JWC_JAKE" connectionStringName="cachestr"/>
</databases>
</sqlCacheDependency>
</caching>
<!--
設置 compilation debug="true" 將調試符號插入 影響性能,因此只在開發過程中將此值
設置為 true。
-->
<compilation debug="true">
<assemblIEs>
<add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
</assemblIEs>
</compilation>
<!--
通過 <authentication> 節可以配置 ASP.Net 使用的 以標識傳入的用戶。
-->
<authentication mode="Forms">
<forms loginUrl="login.ASPx" name=".AJSUPCXAIUTH"></forms>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
<!-- 則通過 <customErrors> 節可以配置相應的處理步驟。具體說來, 要顯示的 Html 錯誤頁
以代替錯誤堆棧跟蹤。-->
<customErrors mode="RemoteOnly" defaultRedirect="/ER3.sHtml">
<error statusCode="403" redirect="/ER1.sHtml" />
<error statusCode="404" redirect="/ER404.sHtml" />
</customErrors>
</system.web>
第二步:在CMD中執行下述命令,以開啟SQL Server數據庫對SqlCacheDependency的支持,利用ASPnet_regsql.exe工具,該工具位於Windows\microsoft.Net\framework\[版本]文件夾中
代碼如下:
vIEw plaincopy to clipboardprint?
ASPnet_regsql -C "data source=127.0.0.1;initial catalog=YD_JWC_JAKE;user id=sa;passWord=" -ed -et -t "T_NewsClass"
ASPnet_regsql -C "data source=127.0.0.1;initial catalog=YD_JWC_JAKE;user id=sa;passWord=" -ed -et -t "T_NewsClass"
參數-C後面跟著的是數據庫連接字符串,注意字母C是大寫。參數-t後面跟著的就是你要開啟數據庫緩存的數據表,此處我為新聞類別的表開啟了緩存依賴。(如果有多個表,則重復執行此命令,注意修改你的數據表名)
第三步:在獲取數據的業務層代碼中,如果是第一次讀取,則從數據庫中讀取後,存入緩存裡。以後獲取數據時,數據庫會自動判斷表是否有更新數據,如果有,則讀數據庫同時更新緩存,如果沒有更新,則從數據庫中讀取。代碼如下:
vIEw plaincopy to clipboardprint?
private void getInfoClass( int t) string CacheKey = "cacheclass" + t.ToString();
object objModle = Jake.DataCache.GetCache(CacheKey);//從緩存中獲取
DataTable dt=null;
if (objModle == null)//如果緩存中沒有則讀取數據庫 Jake.BLL.NewsManage.NewsClass nc = new Jake.BLL.NewsManage.NewsClass();
dt = nc.GetList("").Tables[0];
objModle = dt;
if (objModle != null) System.Web.Caching.SqlCacheDependency dep = new System.Web.Caching.SqlCacheDependency("YD_JWC_JAKE", "T_NewsClass");
Jake.DataCache.SetCache(CacheKey, objModle, dep); }
else dt = (DataTable)objModle; //緩存中有就直接讀取緩存,不需要訪問數據庫 DataRow[] drs = dt.Select("","classid");
StringBuilder sb =new StringBuilder();
sb.Append("<ul>");
foreach (DataRow r in drs) string cid=r["ClassId"].ToString();
Security JS = new Security();
string decrystr = Jake.Common.ConfigHelper.GetConfigString("DecryStr");//獲得加密密鑰
cid = JS.EncryptQueryString(cid, decrystr);
string cdesc=r["ClassDesc"].ToString();
if (t == 1) sb.Append("<li><a href="/Info" + cid + ".shtml" mce_href="Info" + cid + ".shtml"><span class='fontbold'>" + cdesc + "</span></a></li>"); else if (t == 2) sb.Append("<li><a href="/File" + cid +".shtml" mce_href="File" + cid +".sHtml"><span class='fontbold'>" + cdesc + "</span></a></li>"); else
sb.Append("<li><a href="/FAQ" + cid + ".shtml" mce_href="FAQ" + cid + ".sHtml"><span class='fontbold'>" + cdesc + "</span></a></li>"); sb.Append("</ul>");
Response.Write(sb); private void getInfoClass( int t) string CacheKey = "cacheclass" + t.ToString();
object objModle = Jake.DataCache.GetCache(CacheKey);//從緩存中獲取
DataTable dt=null;
if (objModle == null)//如果緩存中沒有則讀取數據庫 Jake.BLL.NewsManage.NewsClass nc = new Jake.BLL.NewsManage.NewsClass();
dt = nc.GetList("").Tables[0];
objModle = dt;
if (objModle != null) System.Web.Caching.SqlCacheDependency dep = new System.Web.Caching.SqlCacheDependency("YD_JWC_JAKE", "T_NewsClass");
Jake.DataCache.SetCache(CacheKey, objModle, dep); }
else dt = (DataTable)objModle; //緩存中有就直接讀取緩存,不需要訪問數據庫 DataRow[] drs = dt.Select("","classid");
StringBuilder sb =new StringBuilder();
sb.Append("<ul>");
foreach (DataRow r in drs) string cid=r["ClassId"].ToString();
Security JS = new Security();
string decrystr = Jake.Common.ConfigHelper.GetConfigString("DecryStr");//獲得加密密鑰
cid = JS.EncryptQueryString(cid, decrystr);
string cdesc=r["ClassDesc"].ToString();
if (t == 1) sb.Append("<li><a href="/Info" + cid + ".shtml" mce_href="Info" + cid + ".shtml"><span class='fontbold'>" + cdesc + "</span></a></li>"); else if (t == 2) sb.Append("<li><a href="/File" + cid +".shtml" mce_href="File" + cid +".sHtml"><span class='fontbold'>" + cdesc + "</span></a></li>"); else
sb.Append("<li><a href="/FAQ" + cid + ".shtml" mce_href="FAQ" + cid + ".sHtml"><span class='fontbold'>" + cdesc + "</span></a></li>"); sb.Append("</ul>");
Response.Write(sb);
}
以上代碼中Jake.DataCache.GetCache()方法是自己定義的一個獲取和設置緩存的通用方法,單獨編譯成了DLL:
代碼如下:
vIEw plaincopy to clipboardprint?
using System;
using System.Collections.Generic;
using System.Web;
using System.Text; namespace Jake public class DataCache /// <summary>
/// 獲取當前應用程序指定CacheKey的Cache值
/// </summary>
/// <param name="CacheKey"></param>
/// <returns></returns>
public static object GetCache(string CacheKey) System.Web.Caching.Cache objCache = HttpRuntime.Cache;
return objCache[CacheKey];
} /// <summary>
/// 設置當前應用程序指定CacheKey的Cache值
/// </summary>
/// <param name="CacheKey"></param>
/// <param name="objObject"></param>
public static void SetCache(string CacheKey, object objObject) System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject); /// <summary> /// </summary>
/// <param name="CacheKey">鍵值</param>
/// <param name="objObject">緩存對象</param>
/// <param name="dep">緩存依賴項</param>
public static void SetCache(string CacheKey, object objObject, System.Web.Caching.CacheDependency dep) System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(
CacheKey,
objObject,
dep,
System.Web.Caching.Cache.NoAbsoluteExpiration,//從不過期
System.Web.Caching.Cache.NoSlidingExpiration,//禁用可調過期
System.Web.Caching.CacheItemPriority.Default,
null } }
using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
namespace Jake public class DataCache /// <summary>
/// 獲取當前應用程序指定CacheKey的Cache值
/// </summary>
/// <param name="CacheKey"></param>
/// <returns></returns>
public static object GetCache(string CacheKey) System.Web.Caching.Cache objCache = HttpRuntime.Cache;
return objCache[CacheKey];
}
/// <summary>
/// 設置當前應用程序指定CacheKey的Cache值
/// </summary>
/// <param name="CacheKey"></param>
/// <param name="objObject"></param>
public static void SetCache(string CacheKey, object objObject) System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject); /// <summary> /// </summary>
/// <param name="CacheKey">鍵值</param>
/// <param name="objObject">緩存對象</param>
/// <param name="dep">緩存依賴項</param>
public static void SetCache(string CacheKey, object objObject, System.Web.Caching.CacheDependency dep) System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(
CacheKey,
objObject,
dep,
System.Web.Caching.Cache.NoAbsoluteExpiration,//從不過期
System.Web.Caching.Cache.NoSlidingExpiration,//禁用可調過期
System.Web.Caching.CacheItemPriority.Default,
null } }
至此,對於數據表的緩存依賴就已經開啟,這樣可以大大加快網站訪問的速度。