I have an ASP.NET e-commerce application. My application has big traffic and I have to use caching system. I switch my cache mechanism from in-memory (memcache) to redis (distributed cache) because I have five servers.
There was no problem with memcache but I have a problem now after to switch redis. For example I serialize my list and it take about 4-5 MB but when I read it from redis-cli so it's fetched very slowly, about 5 seconds and my application raises timeout exception therefore.
I read that "do not store big data in redis". In other hand I use output cache and session cache with MVC for redis there is no problem. Should I use BinarySerializer or what? How can I store big objects in redis cache?
Thanks in advice.
public List<ProdFilter> GetAll(int prodFeatureGroupId)
{
var cacheKey = string.Format("{0}_{1}_{2}",
"ProductRepository",
"GetAll",
prodFeatureGroupId);
var isExists = _cache.Contains(cacheKey) && Const.CacheIsActive;
List<ProdFilter> obj;
if (isExists)
{
obj = _cache.Get<List<ProdFilter>>(cacheKey);
}
else
{
obj = _db.ProdFilters
.Where(x => x.ProdFilterGroupId == prodFeatureGroupId)
.ToList();
_cache.Add(cacheKey, obj);
}
return obj;
}
//my cache methods
private void Create()
{
if (null == _db)
{
ConfigurationOptions option = new ConfigurationOptions();
option.Ssl = false;
option.EndPoints.Add(_host, _port);
var connect = ConnectionMultiplexer.Connect(option);
_db = connect.GetDatabase();
}
}
public void Add<T>(string key, T obj)
{
var data = Serialize(obj);
_db.StringSet(key, data);
}
public void Set<T>(string key, T obj)
{
Add(key, obj);
}
public T Get<T>(string key)
{
var val = _db.StringGet(key);
return Deserialize<T>(val);
}
// my serialize helper
public static byte[] Serialize(object o)
{
if (o == null)
{
return null;
}
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, o);
byte[] objectDataAsStream = memoryStream.ToArray();
return objectDataAsStream;
}
}
public static T Deserialize<T>(byte[] stream)
{
if (stream == null)
return (default(T));
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream(stream))
{
T result = (T)binaryFormatter.Deserialize(memoryStream);
return result;
}
}