1

我正在尝试存储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;
    }
4

1 回答 1

3

将其解析为数组或列表,并以与T.

using System.Linq;

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

对于事物列表,请注意不要在 Memcached 上达到每个键的 2MB 内存最大值,如果您为键启用了磁盘备份,则为 10MB。

实际上,我们通过存储byte[]和使用自定义序列化(有时是自制的,有时是 ProtoBuf)来解决这个问题,以保持快速和轻便。

于 2012-07-31T15:11:46.080 回答