I’m trying to store IEnumerable<T> into memcached, however, I have only been able to successfully store only an instance of T.
Is there different code for storing an enumeration in memcached?
public IEnumerable<UsContentView> GetContentViewByUserId(int userId)
{
Expire("contentViewUserId_" + userId);
var result = Memcached.Get<IEnumerable<UsContentView>>("contentViewUserId_" + userId);
if (result == null)
{
result = db.UsContentViews.Where(m => m.UserID == userId).OrderBy(m => m.ArticleId).Distinct();
var arr = result.ToArray();
var arrList = arr.ToList();
//store it in the cache, with the key
StoreList(arrList, "contentViewUserId_" + userId);
MemoryStream mem = new MemoryStream();
BinaryFormatter b = new BinaryFormatter();
try
{
b.Serialize(mem, result);
}
catch (EntitySqlException ex)
{
throw new ApplicationException("The object query failed", ex);
}
catch (EntityCommandExecutionException ex)
{
throw new ApplicationException("The object query failed", ex);
}
catch (SerializationException ex)
{
throw new ApplicationException("The object graph could not be serialized", ex);
}
}
return result;
}
Resolve it to an array or list and store in the same manner as
T.With lists of things, be careful not to hit the 2MB per key in-memory maximum on Memcached, 10MB if you have disk-backing enabled for keys.
We actually get around this by storing
byte[]and using custom serialization (sometimes home-brew, sometimes ProtoBuf) to keep things speedy and light.