【问题标题】:Is HttpRuntime.Cache the best way to store global settings in ASP.Net?HttpRuntime.Cache 是在 ASP.Net 中存储全局设置的最佳方式吗?
【发布时间】:2015-02-25 09:27:45
【问题描述】:

我们的 ASP.Net 应用程序使用在整个应用程序中使用的各种全局设置。设置作为键/值对存储在数据库中。

在应用程序启动事件中,我们将它们加载到HttpRuntime.Cache 对象中,然后根据需要使用它们。所有设置都通过一个类处理。这是该类的简化代码。

Public Class ConfigClass

    ' Other variables, properties & methods removed for clarity
    ' Functions in DAL are not shown here

    ' Called from Application Start event    
    Public Shared Sub LoadAppConfig()
        Dim lCfg As DataTable = DAL.GetDataTable("Select ConfigID, Value from AppConfig Order By ConfigID")
        If lCfg IsNot Nothing Then
            For li_Lp As Integer = 0 To lCfg.Rows.Count - 1
                HttpRuntime.Cache.Add(lCfg.Rows(li_Lp)("ConfigID").ToString, lCfg.Rows(li_Lp)("Value").ToString, Nothing, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, Caching.CacheItemPriority.NotRemovable, Nothing)
            Next
            lCfg = Nothing
        End If
    End Sub

    ' Returns the value of a single setting
    Public Shared Function GetAppConfig(ByVal as_ConfigID As String) As String
        If HttpRuntime.Cache(as_ConfigID) Is Nothing Then  ' If nothing in cache, try DB
            Dim lOBj As Object = DAL.ExecuteSQL("Select Value from AppConfig Where ConfigID=@ConfigID", DAL.SQLType.sqlScalar, Nothing, "@ConfigID", as_ConfigID).Scalar
            If lOBj Is Nothing Then   ' If no such setting, return empty string
                Return String.Empty
            Else    ' If found, add to cache and return
                HttpRuntime.Cache.Add(as_ConfigID, lOBj.ToString, Nothing, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, Caching.CacheItemPriority.NotRemovable, Nothing)
                Return lOBj.ToString
            End If
        Else
            Return HttpRuntime.Cache(as_ConfigID).ToString
        End If
    End Function

    ' Method to delete a setting
    Public Shared Sub DeleteAppConfig(ByVal as_ConfigID As String)
        If DAL.ExecuteSQL("Delete From AppConfig Where ConfigID=@ConfigID", DAL.SQLType.sqlNQ, Nothing, "@ConfigID", as_ConfigID).IsSuccess Then HttpRuntime.Cache.Remove(as_ConfigID)
    End Sub

End Class

代码运行良好,我没有遇到任何问题。应用程序启动时,大约有 30 个设置加载到缓存中。

有没有更好的方法来存储和访问“全局”设置?无论如何我可以改进这一点吗?

【问题讨论】:

  • 全局设置必须存储在文件或数据库中。其余所有可能不是“全局”的,但会在许多实例上中断 - 取决于您如何设置您的 asp.net 池
  • 是的,在这种情况下,它们存储在数据库中。但为了避免每次设置都访问数据库,我已将它们加载到 HttpRuntime 缓存中,然后使用缓存来读取设置。
  • 如果您的全局设置完全没有改变(直到下次池重新启动),那么您可以使用缓存。
  • 全局设置可以更改 - 有一种方法可以更新全局设置,可以在数据库和缓存中更新它。

标签: asp.net vb.net caching httpruntime.cache


【解决方案1】:

它可能是最好的 - 但是现代数据库系统非常擅长将经常请求的数据缓存到内存中。因此,在具有大量内存备用的系统上,它可能没有太大区别。

【讨论】:

    猜你喜欢
    • 2010-10-01
    • 2010-12-05
    • 2019-11-27
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多