碧空雪狐

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

数据库缓存依赖应用了Cache类,看了这么多篇文章,当时都被忽悠住了,一直以为数据库修改过后,缓存数据也随之改变,希望新手不要这么人为,所谓数据库缓存依赖其实就是让应用程序中的缓存与数据库某表数据建立依赖关系,当数据库数据变化时通知给应用程序,并让应用程序中对应依赖的Cache数据失效(=null)。就是这么一个简单的过程,用户可以通过判断cache是否存在,如果不存在则重新加载数据项。简单的说就是一个数据变化通知的过程,并不会直接改变缓存数据。下面【第三步的】代码可能有错误,大致是这样的,具体没有调试,很简单,用户自我理解一下就可以了。

提炼的精简方法如下:

一. 修改 web.config 的<system.web>节:

1.数据库连接字符串

<connectionStrings>

<add name="OAMisc_ConnectionString" connectionString="Database=SystemOA;server=66.116.111.112;User ID=sa;Password=sa;" providerName="System.Data.SqlClient"/>

</connectionStrings>

2.在<system.web>中添加如下配置信息,*注意:“name” 对应数据库名称;“connectionStringName” 对应连接字符串名称。

<system.web>

<caching>
<sqlCacheDependency enabled="true" pollTime="6000">
<databases>
<add name="SystemOA_221_110911" connectionStringName="OAMisc_ConnectionString"/>
</databases>
</sqlCacheDependency>
</caching>

<system.web>

 

二. 执行命令

开始→运行→CMD→找到自己C\windows\.......的framework对应版本的目录(里面有个aspnet_regsql.exe文件),输入命令:

aspnet_regsql -C "data source=66.116.111.112;initial catalog=SystemOA;user id=sa;password=sa" -ed -et -t "UserInfos"

注释:“data source”:数据源IP地址,“initial catalog”:数据库名称 , “-t”:需要缓存依赖的表名

 

三. 程序中使用依赖缓存

示例:新建了一个页面,后台代码如下。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Caching;

public partial class _Default : System.Web.UI.Page
{
/// <summary>
/// 获取当前应用程序指定Key的缓存对象值
/// </summary>
/// <param name="cacheKey">缓存的键</param>
/// <returns>返回缓存对象的值</returns>
public static object GetCache( string cacheKey )
{
Cache myCache = HttpRuntime.Cache;
return myCache[ cacheKey ];
}

//添加缓存数据

public static void AddCache( string cacheKey , object cacheValue , CacheDependency dep )
{
Cache myCache = HttpRuntime.Cache;
myCache.Insert( cacheKey , cacheValue , dep , Cache.NoAbsoluteExpiration , Cache.NoSlidingExpiration , CacheItemPriority.Default , null );
}

// 页面处理

protected void Page_Load(object sender, EventArgs e)
{
string cacheKey = "ke1";

DateTime nowDate = DateTime.Now;
object objModel = GetCache( cacheKey ); //先获取缓存中的数据
if ( objModel==null ) //缓存失效,则重新加载缓存数据
{
nowDate = DateTime.Now; //以当前时间作为一个缓存失效的标记。

System.Web.Caching.SqlCacheDependency sqlDep = new System.Web.Caching.SqlCacheDependency( "SystemOA" , "frame_config" );
AddCache( "测试key" , "测试值" , sqlDep );

}
Label1.Text = nowDate.ToString( ); 
}
}

 

 

 

posted on 2012-03-15 16:15  碧空雪狐  阅读(384)  评论(0编辑  收藏  举报