2011-07-07 90 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是主數據存儲。 –