65.9K
CodeProject 正在变化。 阅读更多。
Home

在 ASP.NET 中缓存静态数据的简单方法

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.50/5 (9投票s)

2008 年 10 月 15 日

CPOL

1分钟阅读

viewsIcon

54871

downloadIcon

307

通过缓存应用程序的查找数据来提高性能

引言

我最近的任务是创建一个 ASP.NET 应用程序,该应用程序从 AS400 DB2 数据库 (IBM) 中检索大部分参考数据。由于 DB2 上的数据每天更新一次,我希望我的应用程序每天只对每个表进行一次数据库调用。在这种情况下,数据将通过夜间批处理过程更新,我需要在每天早上更新我的数据。

目的

本文将演示一种高效的方法来保持查找数据的缓存。请注意,此示例设计用于较小的数据集。将大量数据保存在内存中可能不是一个好主意,但此示例对较小的表非常有效。此示例使用您可以从 此处 下载的 Northwind 数据库。

要运行示例,您必须更改 web.config 中的连接字符串“NorthwindConnectionString”,使其指向您 Northwind 的副本。

Using the Code

此示例设计用于返回每天更新的数据。在我的生产应用程序中,数据是从 DB2 调用的。为了简单起见,并且为了让任何人都可以运行该示例,此示例使用 SQL Server 代替。

//Returns the next 6:00AM when the data will have been updated.            
private static DateTime cacheExpirationDateTime

{  get 
  {
   if (DateTime.Now.Hour < 6)
      return DateTime.Today.AddHours(6);    
   else
      return DateTime.Today.AddDays(1).AddHours(6);
   }
}        

private static DataTable dtTerritories
{  get
   {
   //Check if the item exists in the Cache, if not add it.
    if (System.Web.HttpContext.Current.Cache["dtTerritories"] == null)
    {
      DataTable dtTerritories = 
      GetLiveData("select * from dbo.Territories order by TerritoryDescription asc");
      dtTerritories.PrimaryKey = new DataColumn[] { dtTerritories.Columns[0] };
      //Add PrimaryKey for good measure. If filter on the key it will be quicker.
      System.Web.HttpContext.Current.Cache.Add(
      "dtTerritories", dtTerritories, null, cacheExpirationDateTime, 
      Cache.NoSlidingExpiration, CacheItemPriority.AboveNormal, null);
     }
   return (DataTable)System.Web.HttpContext.Current.Cache["dtTerritories"];
   }
}

//Use a DataView to avoid making database calls on static data
public static DataTable getTerritories(int regionID)
{
DataView dv = new DataView(dtTerritories);
dv.RowFilter = "RegionID = " + regionID.ToString();
return dv.ToTable();
} 

其他选项

这个示例显然不是唯一的方法。ASP.NET 提供了许多访问/存储数据的方式。本文只是其中一种简单的方法……在这种情况下,我为了简单和编码方便而返回了 DataTables。在我的实际项目中(不是这个示例),我已经完成了我的 AS400 (DB2) DataAccess 类,它可以在不到 2 小时的时间内从 10 个参考表中返回数据!

历史

  • 2008 年 10 月 15 日:初始发布
在 ASP.NET 中缓存静态数据的简单方法 - CodeProject - 代码之家
© . All rights reserved.