0

我们的 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 个设置加载到缓存中。

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

4

1 回答 1

0

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

于 2014-12-29T12:34:53.317 回答