简体   繁体   English

ASP.NET中的SQL Server数据缓存

[英]SQL Server data caching in ASP.NET

I am trying to use caching to save time refreshing my web application and do so automatically whenever the database changes, and am having trouble setting up the cache. 我试图使用缓存来节省刷新我的Web应用程序的时间,并且每当数据库更改时都会自动这样做,并且在设置缓存时遇到了麻烦。

I have added the following code to where I access SQL... 我已将以下代码添加到访问SQL的位置...

SqlDependency.Start("Data Source=" + serverName + ";" + 
                    "Initial Catalog=...;" + "User Id=...;Password=...;");

and then after the SQL connection is made and just before I pull data from SQL... 然后在建立SQL连接之后,就在我从SQL提取数据之前...

SqlCacheDependency dependency = new SqlCacheDependency(command);

int numberOfMinutes = 3;
DateTime expires = DateTime.Now.AddMinutes(numberOfMinutes);

Current.Response.Cache.SetExpires(expires);
Current.Response.Cache.SetCacheability(HttpCacheability.Public);
Current.Response.Cache.SetValidUntilExpires(true);
Current.Response.AddCacheDependency(dependency);

Previously in the method that this code is in, I accessed SQL and returned a list of objects from SQL. 以前,在此代码所在的方法中,我访问了SQL,并从SQL返回了对象列表。 What further steps do I need to do to set up the cache? 我需要做什么进一步的步骤来设置缓存? I'm assuming I have to add the data to the cache somehow and then retrieve it from the cache somehow? 我假设我必须以某种方式将数据添加到缓存,然后以某种方式从缓存中检索数据?

You can use the HttpRuntime.Cache cache object 您可以使用HttpRuntime.Cache缓存对象

I would write a generic method to GET and SET cache object. 我将为GETSET缓存对象编写一个通用方法。

 public T GetOrSetCache<T>
    (string key,T obj, int cacheTime) where T:class,new()
{
    System.Web.Caching.Cache cacheContainer = HttpRuntime.Cache;
    T cacheObj = cacheContainer.Get(key) as T;

    if (cacheObj == null)
    {
        cacheContainer.Insert(key,
            obj,
            null, 
            DateTime.Now.AddMinutes(cacheTime),
            System.Web.Caching.Cache.NoSlidingExpiration);
        cacheObj = obj;
    }

    return cacheObj;
}

When you want to use cache you can do like this on your main code 当您要使用缓存时,可以在主代码上执行此操作

var data = [read data from data base]
int numberOfMinutes = 3;
data = GetOrSetCache("name1",data,numberOfMinutes );

HttpRuntime.Cache HttpRuntime.Cache

NOTE 注意

  1. Cache is a key/value` collection Cache是键/值的集合

  2. Get instance from cache you need to provide a key. cache获取实例,您需要提供一个密钥。

  3. Set instance into cache you need to provide a key and instance object. 将实例设置到cache您需要提供一个键和实例对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM