redis缓存的序列化列表和大对象

8ljdwjyq  于 2021-06-09  发布在  Redis
关注(0)|答案(0)|浏览(255)

我有一个asp.net电子商务应用程序。我的应用程序有很大的流量,我必须使用缓存系统。我将缓存机制从内存(memcache)切换到redis(分布式缓存),因为我有五台服务器。
memcache没有问题,但我现在在切换redis之后遇到了一个问题。例如,我序列化了我的列表,它大约需要4-5 mb,但是当我从redis cli读取它时,它的获取速度非常慢,大约需要5秒,因此我的应用程序会引发超时异常。
我读到“不要在redis中存储大数据”。另一方面,我使用输出缓存和会话缓存与mvc的redis没有问题。我应该使用binaryserializer还是什么?如何在redis缓存中存储大对象?
谢谢你的建议。

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;
        }
    }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题