关于缓存的问题

lunhuifengzheng lunhuifengzheng 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
请问 HttpRuntime.Cache.Insert(cacheKey, ds, dependency,?, ?);
后面两个参数应如何写才可数据库变动时,及时响应到程序中的缓存的更新,而且在用户连续操作时,缓存不释放,不连续操作时,则释放缓存。是否与这有关。如果不是,请教方法。谢谢!如下是我的代码,请教应如何修改,谢谢。忘了说我在SQL2008也开启了service broker。

//DAL.CacheData.cs
namespace DAL
{
public class CacheData
{

private string _source;
///<summary>
///指示数据从何而来
///</summary>
public string Source
{
set { _source = value; }
get { return _source; } }

public CacheData()
{

_source = "未知类型";
}


///<summary>
///从缓存中获取数据
///</summary>
public DataSet GetDataFromCache()
{


string cacheKey = ConfigurationManager.AppSettings["TCM_sys_user"].ToString();
string connString = ConfigurationManager.ConnectionStrings["TCM"].ConnectionString;
//SqlCacheDependencyAdmin.EnableNotifications(connString);
if (HttpRuntime.Cache[cacheKey] != null)
{ _source = "从缓存中取得";
return (DataSet)HttpRuntime.Cache[cacheKey];

}
else
{
SqlDependency.Start(connString);
DataSet ds = new DataSet();


string sqlGetAllUser = "select * from sys_user";
using (SqlConnection conn = new SqlConnection(connString))
{ //SqlDataAdapter da = new SqlDataAdapter(cmd);
// DataSet ds = new DataSet();
// da.Fill(ds);
// DataView dv = ds.Tables[0].DefaultView;
using (SqlCommand cmd = new SqlCommand(sqlGetAllUser, conn))
{
SqlCacheDependency dependency = new SqlCacheDependency(cmd);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
//SqlDependency.Start(connString);
da.Fill(ds);
}

HttpRuntime.Cache.Insert(cacheKey, ds, dependency,DateTime.Now.AddMinutes(30), TimeSpan.Zero);



}

}
_source = "从表中取得";
return ds;

}
}



}
}


//sqlcachedependency.sqldependency.aspx
namespace sqlcachedependency
{
public partial class sqldependency : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

DAL.CacheData cacheData = new DAL.CacheData();
gvShowUser.DataSource = cacheData.GetDataFromCache();
gvShowUser.DataBind();
lbl_source.Text = cacheData.Source;
HyperLink1.NavigateUrl = "index.aspx";
}
}
}


//sqlcachedependency.Global.asax
namespace sqlcachedependency
{
public class Global : System.Web.HttpApplication
{

protected void Application_Start(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["TCM"].ConnectionString;
SqlDependency.Start(connString);
}

protected void Session_Start(object sender, EventArgs e)
{

}

protected void Application_BeginRequest(object sender, EventArgs e)
{

}

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{

}

protected void Application_Error(object sender, EventArgs e)
{

}

protected void Session_End(object sender, EventArgs e)
{

}

protected void Application_End(object sender, EventArgs e)
{

string connString = ConfigurationManager.ConnectionStrings["TCM"].ConnectionString;
SqlDependency.Stop(connString);
}
}
}
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
lunhuifengzheng
.NET社区 62,272 成员 668,968 内容