Introducción
Al ser un servicio de Microsoft Azure, el servicio de caché en Redis es accesible desde una API REST, pero, ¿para qué tomarnos el trabajo de acceder de esta forma si tenemos disponibles librerías de alto nivel que nos ayudan en esta tarea?
La gente de Stack Exchange (si, los dueños de Stack Overflow) creó una librería, open source y altamente performante, para acceder a Redis (algo que ellos usan mucho para sus propios servicios), llamada StackExchange.Redis. En este post vamos a estar viendo cómo acceder a nuestro servicio de caché en Redis utilizando esta librería.
Para saber como crear el servicio de caché de Redis en Azure, pueden ver mi post de Introducción a Redis Cache.
Instalando la librería en nuestro proyecto
Lo primero que vamos a necesitar es instalar el paquete NuGet de StackExchange.Redis. Con esto ya podremos empezar a escribir nuestro código para acceder a la caché.
Accediendo a la caché
Lo primero que necesitamos es crear un ConnectionMultiplexer:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string app = "<tu nombre>.redis.cache.windows.net"; | |
string key = "<key obtenida del portal>"; | |
ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(string.Format("{0},ssl=true,password={1}", app, key)); |
Luego, obtenemos el acceso a la caché, con la función GetDatabase:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
IDatabase cache = connection.GetDatabase(); |
Almacenando y obteniendo los datos
Finalmente podremos almacenar y obtener, por ejemplo, cadenas de texto de la caché fácilmente con las funciones SetString y GetString:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Almacena un valor con la key MiKey | |
cache.StringSet("MiKey", "Valor a almacenar"); | |
// Obtiene nuevamente el valor almacenado | |
string valor = cache.StringGet("MiKey"); |
Si lo que queremos es trabajar con objetos más complejos, les dejo aquí una serie de extensiones que se encargan de serializar y deserializar nuestros objetos, para hacerles la vida un poco más simple:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Newtonsoft.Json; | |
using StackExchange.Redis; | |
namespace RedisCache | |
{ | |
public static class CacheExtensions | |
{ | |
public static T Get<T>(this IDatabase cache, string key) | |
{ | |
return Deserialize<T>(cache.StringGet(string.Format("{0}-{1}", typeof(T).Name, key))); | |
} | |
public static object Get(this IDatabase cache, string key) | |
{ | |
return Deserialize<object>(cache.StringGet(key)); | |
} | |
public static void Set(this IDatabase cache, string key, object value) | |
{ | |
cache.StringSet(key, Serialize(value)); | |
} | |
public static void Set(this IDatabase cache, string key, object value, TimeSpan expiration) | |
{ | |
cache.StringSet(key, Serialize(value), expiration); | |
} | |
public static void Set<T>(this IDatabase cache, string key, T value) | |
{ | |
cache.StringSet(string.Format("{0}-{1}", typeof(T).Name, key), Serialize(value)); | |
} | |
public static void Set<T>(this IDatabase cache, string key, T value, TimeSpan expiration) | |
{ | |
cache.StringSet(string.Format("{0}-{1}", typeof(T).Name, key), Serialize(value), expiration); | |
} | |
static string Serialize<T>(T o) | |
{ | |
if (o == null) | |
{ | |
return null; | |
} | |
return JsonConvert.SerializeObject(o); | |
} | |
static T Deserialize<T>(string objectString) | |
{ | |
if (string.IsNullOrWhiteSpace(objectString)) | |
{ | |
return default(T); | |
} | |
return JsonConvert.DeserializeObject<T>(objectString); | |
} | |
} | |
} |
Funciones avanzadas
También podremos usar funciones más avanzadas, como el agregar un elemento a una lista:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cache.ListLeftPush("MiLista", "Nuevo valor"); |
Hay muchas más opciones disponibles, las cuales les recomiendo ver directamente desde la documentación StackExchange.Redis.
Happy coding!
Pingback: Introducción a Redis Cache | Guillermo Bellmann
pero de donde saco la interfas database