using System;
using System.Web;
using System.Configuration;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Web.Script.Serialization;
using System.Xml.Linq;
using System.Text;
using System.Xml.Serialization;
using StackExchange.Redis;
namespace Neo.Afx.Common
{
///
/// Cache provider for Azure Redis cache service
///
public class CacheContextRedis : ICacheContext
{
private ConnectionMultiplexer _connection;
private IDatabase _cache;
readonly static JavaScriptSerializer Serializer = new JavaScriptSerializer()
{
MaxJsonLength = Int32.MaxValue,
RecursionLimit = 100
};
///
/// Default constructor
///
public CacheContextRedis()
{
if (_connection == null)
{
Connect();
}
}
private void Connect()
{
_connection = ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["RedisConnection"].ToString());
_cache = _connection.GetDatabase();
}
///
/// Get the cached value based on a specified key
///
///
///
///
public T Get(string key)
{
if (_connection == null || _connection.IsConnected == false)
{
Connect();
}
if (_cache == null)
{
return default(T);
}
else
{
if (_cache.KeyExists(key))
{
var value = _cache.StringGet(key);
if (!value.HasValue)
{
return default(T);
}
else
{
return (T)SerializationUtilities.Deserialize(value);
}
}
else
{
return default(T);
}
}
}
///
/// Set the cached value
///
///
///
///
public void Set(string key, object value, int cacheExpirationMinutes)
{
if (_connection == null || _connection.IsConnected == false)
{
Connect();
}
if (_cache != null)
{
if (value != null)
{
try
{
_cache.StringSet(key, SerializationUtilities.Serialize(value), TimeSpan.FromMinutes(cacheExpirationMinutes));
}
catch { }
}
}
}
///
/// Remove a cached value
///
///
public void Remove(string key)
{
if (_connection == null || _connection.IsConnected == false)
{
Connect();
}
if (_cache != null)
{
_cache.KeyDelete(key);
}
}
///
/// Clear the cache
///
public void Clear()
{
if (_connection == null || _connection.IsConnected == false)
{
Connect();
}
var endPoints = _connection.GetEndPoints();
if (endPoints.Length > 0)
{
var server = _connection.GetServer(endPoints[0]);
if (server != null)
{
try
{
server.FlushDatabase();
server.FlushAllDatabases();
}
catch { } //silent fall through
}
}
}
}
}