缓存依赖的实现

1开启sqlserver的缓存监听:找到vs的command管理窗口

在里面 输入一下脚本

aspnet_regsql -C "data source=.;initial catalog=testdata;user id=sa;password=123" -ed -et -t "BaseUser"对指定的表开启监听

2配置webconfig

在webconfig中添加

<caching>
<sqlCacheDependency enabled="true">
<databases>
<add name="CacheDependency_NHibernateSampleDb" connectionStringName="TestData" pollTime="1500"/>
</databases>
</sqlCacheDependency>
</caching>

注意:connectionStringName指定的是链接字符创中的name属性

3封装方法

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace CacheDemo.Controllers
{
    public static class CommonController
    {
        #region 轮询 缓存
        public static DataSet GetCacheData(string CacheName, string TableName, string sqlStr)
        {
            System.Web.Caching.Cache Cache = HttpRuntime.Cache;
            //要检测的数据库
            System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(
                System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
            //初检测数据库中要检测的表
            System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(
                System.Configuration.ConfigurationManager.AppSettings["ConnectionString"], TableName);
            System.Web.Caching.SqlCacheDependency scd = new System.Web.Caching.SqlCacheDependency("CacheDependency_NHibernateSampleDb", TableName);
            SqlDependency.Start(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);

            //此处可以加入自己的其它方法,如重新从数据库取得资料
            DataSet ds = new DataSet();
            using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]))
            {
                string sql = sqlStr;

                using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
                {
                    System.Web.Caching.SqlCacheDependency dependency = new System.Web.Caching.SqlCacheDependency(command);

                    using (System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter()) //查询数据
                    {
                        adapter.SelectCommand = command;
                        adapter.Fill(ds);
                    }
                    Cache.Insert(CacheName, ds, scd);
                }

            }
            return ds;
        }
        #endregion
        // <summary> 
        /// DataTable转为json 
        /// </summary> 
        /// <param name="dt">DataTable</param> 
        /// <returns>json数据</returns> 
        public static string ToJson(DataTable dt)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    result.Add(dc.ColumnName, dr[dc]);
                }
                list.Add(result);
            }

            return SerializeToJson(list);
        }
        /// <summary>
        /// 序列化对象为Json字符串
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <param name="recursionLimit">序列化对象的深度,默认为100</param>
        /// <returns>Json字符串</returns>
        public static string SerializeToJson(this object obj, int recursionLimit = 100)
        {
            JavaScriptSerializer serialize = new JavaScriptSerializer();
            serialize.RecursionLimit = recursionLimit;
            string str = serialize.Serialize(obj);
            str = Regex.Replace(str, @"\\/Date\((\d+)\)\\/", match =>
            {
                DateTime dt = new DateTime(1970, 1, 1);
                dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
                dt = dt.ToLocalTime();
                return dt.ToString("yyyy-MM-dd HH:mm:ss");
            });
            return str;
        }
    }
}

 

你可能感兴趣的:(缓存依赖的实现)