我们的ASP.Net应用程序使用在整个应用程序中使用的各种全局设置。设置作为键/值对存储在数据库中。
在Application start事件中,我们将这些加载到HttpRuntime.Cache
对象中,然后根据需要使用它们。所有设置都通过Class处理。这是该类的简化代码。
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个设置加载到缓存中。
有没有更好的存储和访问“全局”设置的方法?无论如何我能改进吗?
答案 0 :(得分:0)
它可能是最好的 - 但是现代数据库系统非常擅长将经常请求的数据缓存到内存中。因此,在具有大量内存备用的系统上,它可能没什么区别。