很多时候,我们服务器的性能瓶颈会是在查询数据库的时候,所以对数据库的缓存非常重要,那么有没有一种方法,可以实现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
                );
        }
    }
}

至此,对于数据表的缓存依赖就已经开启,这样可以大大加快网站访问的速度。

(转载请注明本文出处:http://blog.csdn.net/j_jake

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/j_jake/archive/2010/04/27/5535874.aspx

 

posted on 2012-04-01 10:37  代岳强  阅读(521)  评论(0编辑  收藏  举报