Clase Auxiliar para Operaciones con Memcached en C#

Para integrar Memcached en un proyecto de Visual Studio, se puede instalar mediante el gestor de paquetes NuGet. Busque "Memcached" en la ventana de paquetes NuGet y seleccione la primera opción para su instalación.

A continuación, se presenta una clase auxliiar que encapusla operaciones comunes de Memcached, diseñada para facilitar la gestión de caché en aplicaciones .NET. El código incluye una enterfaz para definir un contrato de caché, la implementación con Memcached y un ejemplo de configuración.

Interfaz de Caché


public interface ICacheProvider
{
    T Retrieve<T>(string claveCache) where T : class;
    void Store<T>(T valor, string claveCache) where T : class;
    void Store<T>(T valor, string claveCache, DateTime fechaExpiracion) where T : class;
    void Remove(string claveCache);
    void ClearAll();
}

Implementación con Memcached


public class GestorCacheMemcached : ICacheProvider
{
    private static readonly MemcachedClient ClienteCache = new MemcachedClient();

    public T Retrieve<T>(string claveCache) where T : class
    {
        try
        {
            return (T)ClienteCache.Get(claveCache);
        }
        catch
        {
            return default(T);
        }
    }

    public void Store<T>(T valor, string claveCache) where T : class
    {
        var modo = KeyExists(claveCache) ? StoreMode.Set : StoreMode.Replace;
        ClienteCache.Store(modo, claveCache, valor, DateTime.Now.AddMinutes(10));
    }

    public void Store<T>(T valor, string claveCache, DateTime fechaExpiracion) where T : class
    {
        var modo = KeyExists(claveCache) ? StoreMode.Set : StoreMode.Replace;
        ClienteCache.Store(modo, claveCache, valor, fechaExpiracion);
    }

    public void Remove(string claveCache)
    {
        ClienteCache.Remove(claveCache);
    }

    public void ClearAll()
    {
        ClienteCache.FlushAll();
    }

    private static bool KeyExists(string clave)
    {
        return ClienteCache.Get(clave) != null;
    }
}

Configuración en el Archivo App.config


<configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration" />
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <sectionGroup name="enyim.com">
        <section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching" />
    </sectionGroup>
</configSections>

<enyim.com>
    <memcached>
        <servers>
            <add address="192.168.1.12" port="11211" />
        </servers>
        <socketPool minPoolSize="10" maxPoolSize="1000" connectionTimeout="00:00:10" deadTimeout="00:02:00" />
    </memcached>
</enyim.com>

Esta configuración establece la dirección IP y el puerto del servidor Memcached, junto con parámetros de conexión como el tamaño del pool y los tiempos de espera. Ajuste estos valores según el entorno de implementación.

Etiquetas: CSharp memcached nuget cache dotnet

Publicado el 6-12 23:29