有时打开与 Redis 的连接需要很长时间。看起来这取决于连接线程的数量,也许还取决于 PC 配置。我在两个具有 4 核 CPU 的工作站上运行 50 个线程的测试,打开连接需要 70-100 毫秒,而在 8 核工作站和 8 核登台服务器上需要 1000-1500 毫秒,有时甚至更多。奇怪的依赖,但它是可复制的。当 IIS 应用程序池重新启动并且所有线程都试图重新连接时,它会导致缓存停机时间之类的事情。我必须改变什么以获得合理的连接时间?
我使用 BookSleeve 客户端,这里是代码示例:
static void Main(string[] args)
{
for (var i = 0; i < threadCount; i++)
threads.Add(new Thread(RunThread));
foreach (var thread in threads)
thread.Start();
foreach (var thread in threads)
thread.Join();
}
static void RunThread()
{
var connection = TryGetConnection();
while (connection == null)
{
connection = TryGetConnection();
}
}
static RedisConnection TryGetConnection()
{
var connection = currentConnection;
if ((connection != null) && (connection.State == RedisConnectionBase.ConnectionState.Open))
return connection;
lock (syncRoot)
{
if ((currentConnection != null) && (currentConnection.State == RedisConnectionBase.ConnectionState.Open))
return currentConnection;
if ((connectionTask != null) && connectionTask.IsCompleted)
connectionTask = null;
if (connectionTask == null)
{
if ((currentConnection != null) && (currentConnection.State == RedisConnectionBase.ConnectionState.Closed))
{
currentConnection.Dispose();
currentConnection = null;
}
if (currentConnection == null)
{
currentConnection = new RedisConnection(
serverAddress,
serverPort,
ioTimeout: (int) operationTimeout.TotalMilliseconds,
syncTimeout: (int) operationTimeout.TotalMilliseconds);
}
if (currentConnection.State == RedisConnectionBase.ConnectionState.New)
currentConnection.Open();
}
}
return null;
}