5

我在 ASP.NET/C#/SQL Server 2012 中运行一个需要缓存一些存储过程查询结果的网站。结果应该有一个绝对过期。有什么选择可以做到这一点?

最好设置 command.ExpirationDateTime = DateTime.Now.AddMinutes(10) 会很棒,但据我所知,这是不可能的。

编辑:数据将从 API 返回,因此无法使用页面或用户控件进行缓存。

4

4 回答 4

1

我不明白您对实际执行缓存的位置的限制,但我假设您可以访问HttpRuntime.Cache? 如果是这种情况,我在博客文章(缓存服务 - 懒惰方式)中编写了一系列用于缓存服务响应的实用程序。

该实用程序的基础是您可以执行以下操作:

   string cacheKey = GenerateCacheKey(myParam); //most likely a derivative of myParam

   if (Cache.IsInCache<MyResultType>(cacheKey))
   {
      return Cache.GetFromCache<MyResultType>(cacheKey);
   }

   var result = GetMyRequestedResult(myParam);
   if (result != null) //or whatever makes sense
   {
      Cache.InsertIntoCacheAbsoluteExpiration(cacheKey, result, DateTime.Now.AddMinutes(0));
   }

   return result;

如果您在两者之间有任何服务,该帖子会显示一个用于与这些服务交互/缓存的可爱类。

于 2012-11-20T15:06:27.093 回答
1

查看企业库缓存应用程序块。这具有您正在寻找的确切功能

缓存应用程序块

    cache.Add(listid.ToString(), list, CacheItemPriority.Normal, null, 
new SlidingTime(TimeSpan.FromMinutes(60)));
于 2012-11-20T13:55:45.807 回答
0

我最终通过将命令文本与参数名称和值合并,从 SqlCommand 创建了一个散列。在将内容放入/从 HttpContext.Current.Cache 对象中/从中获取内容时,我用作缓存键的那个哈希值。工作正常。可能不是超级快,但是由于某些查询要慢得多,所以没关系。

于 2012-11-21T08:02:59.300 回答
0

您还可以从 .Net Framework 4 开始使用 System.Runtime.Caching.ObjectCache,而不仅仅是在 Web 应用程序中。这是一个例子:

List<EmailData> result = null;

ObjectCache cache = MemoryCache.Default;
var key = string.Concat(title, ":", language);
var item = cache.GetCacheItem(key);

if (item != null)
  return item.Value as List<EmailData>;

using (var connection = _connectionFactory.OpenConnection())
{
  result = connection.Query<EmailData>(sql, new { title, language }).ToList();
}

var cachingPolicy = new CacheItemPolicy
{
  AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(_cacheExpirationIntervalInMinutes)
};

cache.Set(new CacheItem(key, result), cachingPolicy);

return result;

你可以阅读更多:https ://msdn.microsoft.com/en-us/library/system.runtime.caching.objectcache(v=vs.110).aspx

于 2016-11-04T13:44:19.553 回答