如何在DNN模块开发中利用缓存机制?

在 Asp.Net开发过程, 缓存是我们经常遇到的问题, 同样在DNN模块开发中利用好缓存无疑对我们开发的模块是有显著性能提升的效果的。而本身DNN核心API就已经为您提供了一个强大的、便于使用的缓存机 制, 用于将需要大量服务器资源来创建的对象存储在内存中。缓存这些类型的资源会大大改进模块应用程序的性能。而该缓存机制是对Asp.Net下的Cache 类的封装和管理, 故使用方法是类似于原有的Asp.Net的缓存机制, 在DNN中主要是由DataCache类负责, 位于DotNetNuke.Common.Utilities命名空间下:

DataCache

从 上图你可以看出DataCache几乎包含DNN所有相关需要缓存操作的方法, 如此一来对我们开发无疑便捷了不少, 比如缓存页面(Tab), 缓存模块(module), 缓存用户信息和缓存文件等等, 在此我将举一个我们最频繁使用的例子, 那就是缓存经常访问到的数据, 比如最新博客帖子信息:

'This attempts to load from cache first, if not found loads into cache
Public Shared Function GetEntryInfo(ByVal entryID As Integer) As EntryInfo
Dim strCacheKey As String = ConfigManager.ENTRYINFO_CACHEKEY_PREFIX & CStr(entryID)
Dim entry As EntryInfo = CType(DataCache.GetCache(strCacheKey), EntryInfo)

If entry Is Nothing Then
entry = EntryController.GetEntry(entryID)
If Not entry Is Nothing Then
DataCache.SetCache(strCacheKey, entry)
End If
End If

Return
entry
End Function

同时需要在更新该帖子时(编辑或删除)清除缓存:

'Resets the cached entry to nothing
Public Shared Sub ResetEntryInfo(ByVal entryID As Integer)
Dim strCacheKey As String = ConfigManager.ENTRYINFO_CACHEKEY_PREFIX & CStr(entryID)
DataCache.RemoveCache(strCacheKey)
End Sub

' for example: delete entry
Public Shared Sub DeleteEntry(ByVal entryID As Integer)
DataService.DeleteEntry(entryID)
' Refresh cache
ResetEntryInfo(entryID)
End Sub

:) Enjoy DNN!

共有0个回答