2011-07-07 73 views
0

我已为Web应用程序(ASP.NET)实施了Redis服务器(用作数据缓存)。在连接之前检测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) 

这是应用程序将对于框在抛出异常之前很长时间。

这怎么能这样做,它会立即抛出?

+0

Redis现在提供这种功能吗?已经有近四年时间了。 – GaTechThomas

回答

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

我已经想到了类似于您的解决方案的东西。我希望客户端API有内置的东西,我想不是这种情况,在这种情况下,我最终可能会按照你的建议。 – Darknight

+0

我会稍等一会儿,看看是否有其他解决方案,如果不是,那么我会标记为已接受。 – Darknight

+0

我不知道任何内置完整重试/失败策略的通用客户端库,可能是因为它与使用量的差别太大 - 该代码适用于可选缓存,但如果redis是主数据存储。 –