使用TestContainers.CosmosDB调用CosmosClient API始终卡住的解决方法
解决TestContainers.CosmosDB与CosmosClient交互无响应问题
针对你在Windows上运行Linux CosmosDB模拟器容器,调用CreateDatabaseIfNotExistsAsync无返回的问题,可通过以下步骤修复:
1. 确保使用容器实例提供的正确连接字符串
不要使用本地Cosmos模拟器的默认连接串,必须从TestContainers创建的cosmosDb实例中获取专用连接字符串:
var connectionString = cosmosDb.GetConnectionString(); var cosmosClient = new CosmosClient(connectionString, clientOptions);
2. 添加容器就绪等待策略
容器启动后服务可能尚未完全初始化,需添加等待策略确保CosmosDB模拟器就绪:
var cosmosDb = new CosmosDbBuilder() .WithImage("mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest") .WithWaitStrategy(Wait.ForUnixContainer() .UntilHttpRequestIsSucceeded(r => r .ForPort(8081) .ForPath("/_explorer/emulator.pem") .WithTimeout(TimeSpan.FromMinutes(2)))) .Build(); await cosmosDb.StartAsync();
3. 优化CosmosClientOptions配置
除现有设置外,添加EnableEndpointDiscovery = false避免端点发现问题,并设置合理超时:
var clientOptions = new CosmosClientOptions { ConnectionMode = ConnectionMode.Gateway, EnableEndpointDiscovery = false, HttpClientFactory = () => { var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator }; return new HttpClient(handler) { Timeout = TimeSpan.FromMinutes(1) // 设置超时避免无限等待 }; } };
完整工作代码示例
// 构建并启动CosmosDB容器 var cosmosDb = new CosmosDbBuilder() .WithImage("mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest") .WithWaitStrategy(Wait.ForUnixContainer() .UntilHttpRequestIsSucceeded(r => r .ForPort(8081) .ForPath("/_explorer/emulator.pem") .WithTimeout(TimeSpan.FromMinutes(2)))) .Build(); await cosmosDb.StartAsync(); // 配置CosmosClient var clientOptions = new CosmosClientOptions { ConnectionMode = ConnectionMode.Gateway, EnableEndpointDiscovery = false, HttpClientFactory = () => { var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator }; return new HttpClient(handler) { Timeout = TimeSpan.FromMinutes(1) }; } }; var connectionString = cosmosDb.GetConnectionString(); var cosmosClient = new CosmosClient(connectionString, clientOptions); // 创建数据库 var dbResponse = await cosmosClient.CreateDatabaseIfNotExistsAsync("MyDatabase"); Console.WriteLine($"数据库创建成功: {dbResponse.Database.Id}");
内容的提问来源于stack exchange,提问作者RKS
相关产品推荐
相关产品推荐

