我正在尝试使用 StackExchange.Redis 库扫描与特定模式匹配的所有 Redis 键。但是,await foreach
在扫描键时,我的代码在语句处挂起。以下是我得到的:
public class DataMigration(IConnectionMultiplexer connection) : IHostedService
{
public async Task StartAsync(CancellationToken cancellationToken)
{
const string pattern = "{hangfire}:recurring-job:EmailNotificationJob:*";
List<RedisKey> keys = [];
var db = connection.GetDatabase();
foreach (var endpoint in connection.GetEndPoints())
{
var server = connection.GetServer(endpoint);
if (!server.IsConnected || server.IsReplica)
{
continue;
}
// Using SCAN for pagination
await foreach (var key in server.KeysAsync(database: db.Database, pattern: pattern).WithCancellation(cancellationToken))
{
keys.Add(key); // this is never reached
}
}
Console.WriteLine($"Found {keys.Count} keys to update."); // this is never reached
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddSingleton<IConnectionMultiplexer>(serviceProvider =>
{
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
const string redisHost = ...
const int redisPort = ...
const string redisPassword = ...
var redisConfiguration = new ConfigurationOptions
{
EndPoints = { $"{redisHost}:{redisPort}" },
Password = redisPassword,
Ssl = true,
AbortOnConnectFail = false, // Keep trying to connect
ConnectTimeout = 15000, // 15 seconds timeout
SyncTimeout = 15000, // 15 seconds timeout for synchronous operations
LoggerFactory = loggerFactory
};
return ConnectionMultiplexer.Connect(redisConfiguration);
});
builder.Services.AddHostedService<DataMigration>();
var app = builder.Build();
app.Run();