如何在memcached中存储IEnumerable <t>的实例?</t>

时间:2012-07-31 15:10:13

标签: c# memcached

我正在尝试将IEnumerable<T>存储到memcached中,但是,我只能成功存储T的实例。

是否有不同的代码用于在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;
    }

1 个答案:

答案 0 :(得分:3)

将其解析为数组或列表,并以与T相同的方式存储。

using System.Linq;

var array = myEnumerable.ToArray();
var list = myEnumerable.ToList();

对于事物列表,请注意不要在Memcached上按内存最大值2MB,如果你为密钥启用了磁盘支持则为10MB。

我们实际上是通过存储byte[]并使用自定义序列化(有时是家庭酿造,有时是ProtoBuf)来保持速度和光线。