asp.net - 连接前检测Redis是否连接

标签 asp.net caching redis

我已经为 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/

相关文章:

python - Openshift 墨盒部署到错误/旧应用程序

asp.net - 是否可以在 ASP.NET 中禁用 Firefox 的离线缓存(在服务器级别)?

c# - ASP.net CORE 相对于 Asp.net 的主要优势

c# - 添加 Windows Azure 缓存会导致 Visual Studio 2012 崩溃,并出现 datacachefactory 参数 null 异常

css - Drupal 8 缓存 css 和 js

PHP 使用网络端口连接到 Redis 服务。 Redis 异常 : No such file or directory

asp.net - 如何在 Sitecore 中以编程方式创建项目

asp.net - Apache 反向代理到 IIS

ios - ASIDownloadCache 清除除某些项目外的所有项目

redis - Redis是否支持将一个key拆分成多个Redis Instance?