SqlCacheDependency的使用方法

本文详细介绍了如何在SQL数据库中启用ServiceBroker服务、配置Global.asax文件以实现缓存,以及使用SqlDependency实现数据缓存的具体代码流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

步骤一:

sql数据库必须开启ServiceBroker服务,首先检测是否已经启用ServiceBroker,检测方法:

Select  DATABASEpRoPERTYEX('数据库名称','IsBrokerEnabled')

--1表示已经启用0表示没有启用

步骤二:

如果ServiceBroker没有启用,使用下面语句启用:

ALTER  DATABASE  <数据库名称>  SET  ENABLE_BROKER;

步骤三:Global.asax的设置

protected void Application_Start(object sender, EventArgs e)
        {
            SqlDependency.Start(ConfigurationManager.AppSettings["ConnectionString"].ToString());
        }

protected void Application_End(object sender, EventArgs e)
        {
            SqlDependency.Stop(ConfigurationManager.AppSettings["ConnectionString"].ToString());
        }

步骤四:缓存实现

使用sqldependency实现缓存的代码:

   public string GetCust()
        {
            string jsonCustInofor=string.Empty;
            //判断是否存在缓存,如果存在就使用
            if (HttpContext.Current.Cache[Cache_CustKey] == null)
            {
                List<Model.ComboxSourceModel> entities = new List<Model.ComboxSourceModel>();
                using (SqlConnection conn = new SqlConnection(DbHelperSQL.connectionString))
                {
                    conn.Open();
                    SqlCommand sqlCommand = new SqlCommand();
                    sqlCommand.CommandType = CommandType.Text;
                    sqlCommand.CommandText = "select ccusCode,ccusName from dbo.Customers";
                    sqlCommand.Connection = conn;
                    SqlCacheDependency scd = new SqlCacheDependency(sqlCommand);
                    SqlDataReader reader = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
                    while (reader.Read())
                    {
                        Model.ComboxSourceModel entity = new Model.ComboxSourceModel();
                        entity.Key = reader["ccusCode"].ToString();
                        entity.Value = reader["ccusName"].ToString();
                        entities.Add(entity);
                    }
                    reader.Close();
                    reader.Dispose();
                    conn.Close();
                    conn.Dispose();
                    if (entities != null && entities.Count > 0)
                    {
                        jsonCustInofor=JsonHelper.Serialize(entities);
                        HttpContext.Current.Cache.Insert(Cache_CustKey, jsonCustInofor, scd);
                    }
                }

            }
            else
            {
                jsonCustInofor = HttpContext.Current.Cache[Cache_CustKey].ToString();
            }
            return jsonCustInofor;
        }
 

注意:

 这里的查询语句中不能出现“*”,表名之前要注明所有者(dbo.Customers


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值