我有一个运行我的 C# 应用程序的 Windows Azure 服务器。它分布在 4 个中等实例上,我使用 Redis 进行 L2 缓存。该应用程序正在处理相当可观的流量(每天大约 300,000 次浏览量)。我使用 BookSleeve 进行 redis 连接,在应用程序启动并运行后,它将开始从 BookSleeve 抛出 SocketExceptions 大约每分钟四次。确切的异常(exception)是:
Exception type: System.Net.Sockets.SocketException
Exception message: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
这似乎只发生在我从服务器读取内容时:
using (var connection = ConnectionGateway.GetReadConnection())
{
var task = connection.Hashes.GetString(App.RedisDatabase, CacheKeys.My_KEY);
var result = connection.Wait(task);
}
我的 GetReadConnection 设置如下:
public static RedisConnection GetReadConnection()
{
RedisConnection conn = getNewConnection();
try
{
var openAsync = conn.Open();
conn.Wait(openAsync);
return conn;
}
catch (SocketException ex)
{
throw new Exception(RedisConnectionFailed, ex);
}
}
现在,我的所有写入都共享一个连接,就像作者描述的那样,因此这只发生在需要使用 connection.Wait() 的读取上。这一切似乎都运作良好。写入使用类似于 Maintaining an open Redis connection using BookSleeve 的代码
我尝试更改 Redis 服务器的超时以适应 Azure 负载均衡器,但没有成功。我已尝试设置超时 30 和设置超时 0,如下所述:Redis connection errors when using Booksleeve Redis client in Azure VM
任何帮助将不胜感激。
最佳答案
看一下代码,首先发生的事情是您似乎正在为每个读取操作创建一个连接。这不是必需的,并且可能会对 .net 和 redis 产生不利影响:BookSleeve 是一个多路复用器 - 它的设计目的是通过单个连接同时处理大量请求。当您调用 Wait 时,只有等待线程会阻塞 - BookSleeve 的内部将继续处理其他线程等。
此外,创建连接有相当大的开销:除了建立新的 TCP 连接的成本之外,BookSleeve 还需要与 Redis 服务器通信以查找正确操作所需的一些关键配置信息,因此始终建议重复使用单个共享连接或少量共享连接。
关于c# - 从 Azure 连接到 Redis 抛出间歇性异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12740479/