我已经为 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)
这是应用程序在抛出异常之前将阻塞很长时间的地方。
如何做到让它立即抛出?
最佳答案
您无法立即检测到网络超时,但可以将影响降至最低。问题是您尝试连接并在每个请求上都超时。试试这个版本 - 如果出现错误,它将在接下来的五分钟内停止尝试使用缓存。
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;
}
关于asp.net - 连接前检测Redis是否连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6607899/