you are here: codestackercodes [RSS] → tag cache [RSS]

Cache em VB.Net

Conjunto de classes para encapsular as operações de inserção, atualização, remoção e busca no cache do Asp.Net, podendo ser adicionados novos gerenciadores de cache, como o Memcache, por exemplo.

Imports System.Web

''' ---------------------------------------------------
''' Interface para as classes de cache.
''' ---------------------------------------------------
Public Interface ICache

    Function GetObject(Of T)(ByVal key As String) As T

    Sub Insert(Of T)(ByVal key As String, ByVal value As T)

    Sub Insert(ByVal key As String, ByVal value As Object)

    Sub Update(Of T)(ByVal key As String, ByVal value As T)

    Sub Update(ByVal key As String, ByVal value As Object)

    Sub Remove(ByVal key As String)

    Sub RemoveAll()

End Interface


''' ---------------------------------------------------
''' AspNetCache - Encapsula as rotinas de cache do ASP.Net
''' ---------------------------------------------------
Public Class AspNetCache
    Implements ICache

    'Objeto System.Web.Caching.Cache
    Private _cache As System.Web.Caching.Cache

    Private dias As Integer

    'Número de dias que o objeto ficará no cache
    Public Property Expire() As Integer
        Get
            Return dias
        End Get
        Set(ByVal value As Integer)
            dias = value
        End Set
    End Property

    Protected Property Cache() As System.Web.Caching.Cache
        Get
            Return _cache
        End Get
        Set(ByVal value As System.Web.Caching.Cache)
            _cache = value
        End Set
    End Property

    'Retorna o número de objetos no cache
    Public ReadOnly Property Count() As Integer
        Get
            Return Me.Cache.Count
        End Get
    End Property

    'Construtor, obtém o gerenciador de cache do contexto web atual.
    Public Sub New()
        Me.Cache = HttpContext.Current.Cache
    End Sub

    'Retorna do cache o objeto do tipo T
    Public Function GetObject(Of T)(ByVal key As String) As T Implements ICache.GetObject
        Dim obj As T
        Try
            obj = DirectCast(Me.Cache(key), T)
        Catch ex As Exception
            Throw
        End Try
        Return obj
    End Function

    'Inserção com generics (tipada)
    Public Sub Insert(Of T)(ByVal key As String, ByVal value As T) Implements ICache.Insert
        Try
            Me.Cache.Insert(key, value, Nothing, Now.AddDays(Me.dias), Caching.Cache.NoSlidingExpiration)
        Catch ex As Exception
            Throw
        End Try
    End Sub

    'Inserção não tipada
    Public Sub Insert(ByVal key As String, ByVal value As Object) Implements ICache.Insert
        Try
            Me.Cache.Insert(key, value, Nothing, Now.AddDays(Me.dias), Caching.Cache.NoSlidingExpiration)
        Catch ex As Exception
            Throw
        End Try
    End Sub

    'Atualização - Remove o antigo e insere o objeto novo (tipada - generics)
    Public Sub Update(Of T)(ByVal key As String, ByVal value As T) Implements ICache.Update
        Try
            'Remove o objeto existente...
            Me.Remove(key)
            '... e insere a nova versão
            Me.Cache.Insert(key, value, Nothing, Now.AddDays(Me.dias), Caching.Cache.NoSlidingExpiration)
        Catch ex As Exception
            Throw
        End Try
    End Sub

    'Atualização - Remove o antigo e insere o objeto novo (não tipada)
    Public Sub Update(ByVal key As String, ByVal value As Object) Implements ICache.Update
        Try
            'Remove o objeto existente...
            Me.Remove(key)
            '... e insere a nova versão
            Me.Cache.Insert(key, value, Nothing, Now.AddDays(Me.dias), Caching.Cache.NoSlidingExpiration)
        Catch ex As Exception
            Throw
        End Try
    End Sub

    'Remove um objeto do cache
    Public Sub Remove(ByVal key As String) Implements ICache.Remove
        Try
            Me.Cache.Remove(key)
        Catch ex As Exception
            Throw
        End Try
    End Sub

    'Remove todos os objetos do cache
    Public Sub RemoveAll() Implements ICache.RemoveAll
        Try
            Dim iterator As IDictionaryEnumerator = Me.Cache.GetEnumerator
            While iterator.MoveNext
                Me.Remove(iterator.Key.ToString)
            End While
        Catch ex As Exception
            Throw
        End Try
    End Sub
End Class


''' ---------------------------------------------------
''' Factory que instancia o objeto de cache de acordo com o argumento passado.
''' ---------------------------------------------------
Public Class CacheFactory

    ''' Tipos de cache
    '''     AspNet: cache do Asp.Net (System.Web.Caching.Cache)
    '''        OBS: outros objetos encapsuladores de cache podem ser criados,
    '''        bastando para isso implementar a extensão ICache. Uma sugestão
    '''        seria criar uma classe para trabalhar com o Memcache usando a
    '''        biblioteca Enyim.Caching.MemcachedClient, disponível em 
    '''        http://www.codeplex.com/EnyimMemcached.
    Enum CacheType
        AspNet
    End Enum

    Public Shared Function GetCache(ByVal type As CacheType) As ICache
        Dim cache As ICache = Nothing
        Select Case type
            Case CacheType.AspNet
                cache = New AspNetCache()
            ' No caso de adicionar mais gerenciadores de cache, inserir 
            ' aqui o código de criação dos objetos.
        End Select
        Return cache
    End Function

End Class
Displaying 1 Code