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
循环而不是lambdas。
每次运行此代码时,都会收到异常The specified endpoint is not defined
我发现这很奇怪,因为我从同一个连接获取端点。返回的端点是正确的。
我在这里做错了什么?
我确实意识到我不应该在每个页面加载时打开一个新连接,但这只是一个不经常访问的管理页面,仅供我使用;所以我并不担心性能开销。此外,我保存的连接隐藏在CacheClass中,该CacheClass抽象出特定的提供者。
答案 0 :(得分:2)
您遇到此错误,因为您的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();
}