c# - StackExchange.ConnectionMultiplexer.GetServer 不工作

标签 c# asp.net redis stackexchange.redis

        using (ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("redisIP:6379,allowAdmin=true"))
        {

            Model.SessionInstances = connection.GetEndPoints()
                .Select(endpoint =>
                {                      
                    var status = new Status();
                    var server = connection.GetServer(endpoint); // Exception thrown here!
                    status.IsOnline = server.IsConnected;
                    return status;
                 });
         }

以上代码运行在 ASP.NET ASPX 页面的代码后面。我在运行良好的命令行程序中运行了非常相似的代码,所以我不确定我在这里做错了什么。唯一的区别是代码使用的是 foreach 循环而不是 lambda。

每次运行这段代码时,我都会得到一个异常The specified endpoint is not defined

我发现这很奇怪,因为我从同一个连接获取端点。返回的端点是正确的。

我在这里做错了什么?


我确实意识到我不应该在每次加载页面时都打开一个新连接,但这只是我不经常访问的管理页面;所以我不担心性能开销。此外,我保存的连接隐藏在 CacheClass 中,该 CacheClass 抽象出特定的提供者。

最佳答案

您遇到此错误是因为您的 lambda 表达式返回的可枚举正在被惰性计算。当您的 lambda 表达式运行时,您的连接已被 using 语句关闭。

using 语句中,你应该执行你的 lambda 表达式,例如通过在末尾添加 .ToList():

using (ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("redisIP:6379,allowAdmin=true"))
{
      Model.SessionInstances = connection.GetEndPoints()
        .Select(endpoint =>
        {
            var status = new Status();
            var server = connection.GetServer(endpoint);
            status.IsOnline = server.IsConnected;
            return status;
        }).ToList();
 }

关于c# - StackExchange.ConnectionMultiplexer.GetServer 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46917437/

相关文章:

C# 条件运算符 - 如果条件为真则调用方法,否则什么都不做

c# - div.Visible 不在其他代码之前执行

asp.net - 如何打开 aspx 页面作为模态弹出窗口

c# - 更改 Visual Studio ASP.NET HTTPS 证书

ruby - 如何使用ruby在redis hash中设置数据

php - predis hmset 嵌套数组值

node.js - ioredis 按模式删除所有键

c# - Linq 对象属性在序列化后消失

c# - 如何调整 Windows 图标覆盖的大小?

asp.net - 从 Controller 构造函数访问 Request.Cookies