【问题标题】:Detect if Redis connection before connecting连接前检测Redis是否连接
【发布时间】:2011-09-30 06:38:13
【问题描述】:

我已经为 Web 应用程序 (ASP.NET) 实现了一个 Redis 服务器(用作数据缓存)。

其中一个设计目标是在 Redis 服务器出现故障时让 Web 应用程序正常运行。

目前这确实有效,但是它非常非常慢

以下是处理 Redis 的类中的代码块:

public string GetCachedData(string k)
    {
        string res = string.Empty;


        if (ConfigurationManager.AppSettings.GetValues("UseMemcache")[0].ToString() == "False")
        {
            return res;
        }

        try
        {
            using (RedisClient rs = new RedisClient(ConfigurationManager.AppSettings.GetValues("RedisServerIP")[0].ToString()))
            {
                byte[] buf = rs.Get(k);

                if (buf != null)
                {
                        res = System.Text.ASCIIEncoding.UTF8.GetString(buf);
                }   
            }
        }
        catch (Exception)
        {
            res = "";
        }

        return res;
    }

问题:

上线

(RedisClient rs = new RedisClient)

这是应用程序在抛出异常之前会长时间阻塞的地方。

如何做到这一点使其立即抛出?

【问题讨论】:

  • Redis 现在是否提供这种类型的功能?已经快四年了。

标签: asp.net caching redis


【解决方案1】:

您无法立即检测到网络超时,但可以将影响降至最低。问题是您尝试连接并获得每个请求的超时。试试这个版本 - 如果出现错误,它将在接下来的五分钟内停止尝试使用缓存。

public DateTime LastCacheAttempt {get;set;}
private bool? UseMemCache {get;set;}

public string GetCachedData(string k)
{
    string res = string.Empty;

    if (UseMemCache == null) {
        UseMemCache = ConfigurationManager.AppSettings.GetValues("UseMemcache")[0].ToString() != "False";
        if (!UseMemCache) LastCacheAttempt == DateTime.MaxValue;
    }

    if (UseMemCache || LastCacheAttempt < DateTime.Now.AddMinutes(-5))
    {

    try
    {
        using (RedisClient rs = new RedisClient(ConfigurationManager.AppSettings.GetValues("RedisServerIP")[0].ToString()))
        {
            byte[] buf = rs.Get(k);

            if (buf != null)
            {
                    res = System.Text.ASCIIEncoding.UTF8.GetString(buf);
            }   
        }
    }
    catch (Exception)
    {
        UseMemCache = false;
        LastCacheAttempt = DateTime.Now;
    }
    }
    return res;
}

【讨论】:

  • 我已经想到了与您的解决方案类似的方法。我希望客户端 API 内置了一些东西。我想情况并非如此,在这种情况下,我可能最终会听从你的建议。
  • 我会再等一会儿,看看是否有其他解决方案浮出水面,如果没有,我会标记为已接受。
  • 我不知道有任何内置了完整重试/失败策略的通用客户端库,可能是因为它在使用方面差异太大 - 该代码适用于可选缓存,但完全不合适如果 redis 是主数据存储。
  • 就我而言,redis 仅充当有效缓存(实际的数据存储只是一个 sql server 后端)我只是希望能够顺利处理 redis 故障转移。
猜你喜欢
  • 1970-01-01
  • 2014-10-03
  • 1970-01-01
  • 2017-08-30
  • 2015-10-19
  • 1970-01-01
  • 2016-02-03
  • 2016-10-20
  • 1970-01-01
相关资源
最近更新 更多