在.net Web应用程序中加载高度重用数据的最佳方法是什么?

时间:2008-09-15 16:09:16

标签: caching global-asax onstart

假设我有一个在网络应用上导航的类别列表。我应该在global.asax的application_onStart中添加一个函数调用,以便将该数据提取到一遍又一遍地重复使用的数组或集合中,而不是从数据库中为evey用户选择。如果我的数据根本没有变化 - (编辑 - 经常),这会是最好的方法吗?

8 个答案:

答案 0 :(得分:2)

您可以将列表项存储在Application对象中。你对application_onStart()是正确的,只需调用一个读取数据库并将数据加载到Application对象的方法。

在Global.asax

public class Global : System.Web.HttpApplication
{
    // The key to use in the rest of the web site to retrieve the list
    public const string ListItemKey = "MyListItemKey";
    // a class to hold your actual values. This can be use with databinding
    public class NameValuePair
    { 
        public string Name{get;set;} 
        public string Value{get;set;}
        public NameValuePair(string Name, string Value)
        {
            this.Name = Name;
            this.Value = Value;
        }
    }

    protected void Application_Start(object sender, EventArgs e)
    {
        InitializeApplicationVariables();
    }


    protected void InitializeApplicationVariables()
    {
        List<NameValuePair> listItems = new List<NameValuePair>();
        // replace the following code with your data access code and fill in the collection
        listItems.Add( new NameValuePair("Item1", "1"));
        listItems.Add( new NameValuePair("Item2", "2"));
        listItems.Add( new NameValuePair("Item3", "3"));
        // load it in the application object
        Application[ListItemKey] = listItems;
    }
 }

现在,您可以在项目的其余部分中访问您的列表。例如,在default.aspx中加载DropDownList中的值:

<asp:DropDownList runat="server" ID="ddList" DataTextField="Name" DataValueField="Value"></asp:DropDownList>

在代码隐藏文件中:

protected override void OnPreInit(EventArgs e)
{
    ddList.DataSource = Application[Global.ListItemKey];
    ddList.DataBind();
    base.OnPreInit(e);
}

答案 1 :(得分:1)

如果它永远不会改变,它可能不需要在数据库中。

如果没有太多数据,您可以将其放在web.config中,或者作为代码中的Enum。

答案 2 :(得分:1)

获取所有内容可能很昂贵。尝试使用lazy init,仅获取请求数据,然后将其存储在缓存变量中。

答案 3 :(得分:1)

过早优化是邪恶的。这是一个给定的,如果您在应用程序中遇到性能问题,并且您希望向用户显示“静态”信息,则可以将该数据一次加载到数组中并将其存储在应用程序对象中。您需要小心并平衡内存使用情况和优化。

您遇到的问题是更改数据库存储信息而不更新缓存版本。您可能希望在数据库中存储某种最后更改日期,并将其与缓存数据一起存储在状态中。这样,您可以查询最大的更改时间并进行比较。如果它比您的缓存日期更新,那么您将其转储并重新加载。

答案 4 :(得分:1)

在应用程序变量中。

请记住,应用程序变量可以包含.Net中的对象,因此您可以在global.asax中实例化该对象,然后直接在代码中使用它。

由于应用程序变量在内存中,因此它们非常快(与必须调用数据库相比)

例如:

// Create and load the profile object
x_siteprofile thisprofile = new x_siteprofile(Server.MapPath(String.Concat(config.Path, "templates/")));
Application.Add("SiteProfileX", thisprofile);

答案 5 :(得分:1)

我会将数据存储在Application Cache(Cache对象)中。而且我不会预加载它,我会在第一次请求时加载它。有关缓存的好处是ASP.NET将对其进行管理,包括为您提供在文件更改,时间段等之后使缓存条目到期的选项。并且由于项目保存在内存中,因此对象不会被序列化/反序列化,因此用法非常快。

用法很简单。 Cache对象上有Get和Add方法,分别检索项目并将其添加到缓存中。

答案 6 :(得分:0)

我将静态集合用作私有,具有公共静态属性,可以从数据库加载或获取它。

此外,您可以添加一个静态日期时间,该日期时间在加载时设置,如果您调用它,经过一段时间后,清除静态集合并重新查询它。

答案 7 :(得分:0)

缓存是要走的路。如果您进入设计模式,请查看单身人士。

但总的来说,我不确定在发现性能下降之前我会担心它。

相关问题