Azure中Redis缓存中的一致超时

时间:2014-10-14 04:03:27

标签: azure redis stackexchange.redis azure-redis-cache

我在一个天蓝色的网站上使用Redis Cache。缓存托管在Azure中。通过我们的监控将值设置到缓存时,我注意到了一些超时。所以我运行了一些负载测试,在我从本地服务器缓存移动到使用redis之前我已经运行了,结果与之前的测试运行相比非常糟糕,主要是由于redis缓存超时。

我正在使用StackExchange.Redis库版本1.0.333强名称版本。

每次访问缓存时,我都小心不要创建新连接。

负载测试实际上没有加载服务器那么多,结果之前100%成功,现在由于超时导致大约50%的错误率。

用于访问缓存的代码。

 public static class RedisCacheProvider
{
    private static ConnectionMultiplexer connection;
    private static ConnectionMultiplexer Connection
    {
        get
        {
            if (connection == null || !connection.IsConnected)
            {
                connection = ConnectionMultiplexer.Connect(ConfigurationManager.ConnectionStrings["RedisCache"].ToString());
            }
            return connection;
        }
    }

    private static IDatabase Cache
    {
        get
        {
            return Connection.GetDatabase();
        }
    }


    public static T Get<T>(string key)
    {
        return Deserialize<T>(Cache.StringGet(key));
    }

    public static object Get(string key)
    {
        return Deserialize<object>(Cache.StringGet(key));
    }

    public static void Set(string key, object value)
    {
        Cache.StringSet(key, Serialize(value));
    }

    public static void Remove(string key)
    {
        Cache.KeyDelete(key);
    }

    public static void RemoveContains(string contains)
    {
        var endpoints = Connection.GetEndPoints();
        var server = Connection.GetServer(endpoints.First());
        var keys = server.Keys();
        foreach (var key in keys)
        {
            if (key.ToString().Contains(contains))
                Cache.KeyDelete(key);
        }
    }

    public static void RemoveAll()
    {
        var endpoints = Connection.GetEndPoints();
        var server = Connection.GetServer(endpoints.First());
        server.FlushAllDatabases();
    }

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

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

}

2 个答案:

答案 0 :(得分:3)

我最近遇到了同样的问题。

有几点可以改善你的情况:

Protobuf-net而不是BinaryFormatter

我建议使用protobuf-net,因为它会减少要存储在缓存中的值的大小。

public interface ICacheDataSerializer
    {
        byte[] Serialize(object o);
        T Deserialize<T>(byte[] stream);
    }

public class ProtobufNetSerializer : ICacheDataSerializer
    {
        public byte[] Serialize(object o)
        {
            using (var memoryStream = new MemoryStream())
            {
                Serializer.Serialize(memoryStream, o);

                return memoryStream.ToArray();
            }
        }

        public T Deserialize<T>(byte[] stream)
        {
            var memoryStream = new MemoryStream(stream);

            return Serializer.Deserialize<T>(memoryStream);
        }
    }

实施重试策略

实现此RedisCacheTransientErrorDetectionStrategy以处理超时问题。

using Microsoft.Practices.TransientFaultHandling;

public class RedisCacheTransientErrorDetectionStrategy : ITransientErrorDetectionStrategy
    {
        /// <summary>
        /// Custom Redis Transient Error Detenction Strategy must have been implemented to satisfy Redis exceptions.
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public bool IsTransient(Exception ex)
        {
            if (ex == null) return false;

            if (ex is TimeoutException) return true;

            if (ex is RedisServerException) return true;

            if (ex is RedisException) return true;

            if (ex.InnerException != null)
            {
                return IsTransient(ex.InnerException);
            }

            return false;
        }
    }

实例化如下:

private readonly RetryPolicy _retryPolicy;

// CODE
var retryStrategy = new FixedInterval(3, TimeSpan.FromSeconds(2));
            _retryPolicy = new RetryPolicy<RedisCacheTransientErrorDetectionStrategy>(retryStrategy);

像这样使用:

var cachedString = _retryPolicy.ExecuteAction(() => dataCache.StringGet(fullCacheKey));

查看代码,以最大限度地减少缓存中存储的缓存调用和值。我通过更有效地存储值来减少大量错误。

如果这些都没有帮助。移动到更高的缓存(我们最终使用C3而不是C1)。

enter image description here

答案 1 :(得分:1)

如果IsConnected为false,则不应创建新的ConnectionMultiplexer。现有的多路复用器将在后台重新连接。通过创建新的多路复用器而不是处理旧的多路复用器,您正在泄漏连接。我们建议使用以下模式:

private static Lazy<ConnectionMultiplexer> lazyConnection =
    new Lazy<ConnectionMultiplexer>(() => {
        return ConnectionMultiplexer.Connect(
            "mycache.redis.cache.windows.net,abortConnect=false,ssl=true,password=...");
    });

public static ConnectionMultiplexer Connection {
    get {
        return lazyConnection.Value;
    }
}

您可以在Azure门户中监控缓存的连接数。如果它看起来异常高,这可能会影响你的表现。

如需进一步帮助,请通过azurecache@microsoft.com'与我们联系。

相关问题