调用Event Hub CreateBatchAsync时连接失败问题求助
按照微软文档创建Azure免费试用版Event Hub后,在.Net示例应用中配置了connectionString和eventHubName,运行代码时调用CreateBatchAsync方法抛出错误:A connection attempt failed because the connected party did not properly respond。尝试了连接字符串和访问控制两种认证方式,均出现相同错误。
示例代码如下:
class Program { const string eventHubName = "<eventHubName>"; const string connectionString = @"<connectionString>"; public static async Task Main(string[] args) { await EventHubIngestionAsync(); } public static async Task EventHubIngestionAsync() { await using (var producerClient = new EventHubProducerClient(connectionString, eventHubName)) { int counter = 0; for (int i = 0; i < 100; i++) { int recordsPerMessage = 3; try { var records = Enumerable .Range(0, recordsPerMessage) .Select(recordNumber => $"{{\"timeStamp\": \"{DateTime.UtcNow.AddSeconds(100 * counter)}\", \"name\": \"{($"name {counter}")}\", \"metric\": {counter + recordNumber}, \"source\": \"EventHubMessage\"}}"); string recordString = string.Join(Environment.NewLine, records); EventData eventData = new EventData(Encoding.UTF8.GetBytes(recordString)); Console.WriteLine($"sending message {counter}"); // Optional "dynamic routing" properties for the database, table, and mapping you created. //eventData.Properties.Add("Table", "TestTable"); //eventData.Properties.Add("IngestionMappingReference", "TestMapping"); //eventData.Properties.Add("Format", "json"); using EventDataBatch eventBatch = await producerClient.CreateBatchAsync(); eventBatch.TryAdd(eventData); IEnumerable<EventData> dd = null; await producerClient.SendAsync(dd); } catch (Exception exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("{0} > Exception: {1}", DateTime.Now, exception.Message); Console.ResetColor(); } counter += recordsPerMessage; } } } }
针对这个连接错误和代码问题,可按以下步骤排查修复:
网络/防火墙拦截
该错误通常是本地防火墙、公司网络或代理阻止了Event Hub的AMQP端口(5671/5672)。可以尝试切换到AMQP over WebSockets(使用443端口,通常不会被拦截),修改客户端初始化代码:var producerOptions = new EventHubProducerClientOptions { TransportType = EventHubsTransportType.AmqpWebSockets }; await using var producerClient = new EventHubProducerClient(connectionString, eventHubName, producerOptions);连接字符串验证
确认连接字符串是Event Hub命名空间的有效连接字符串(而非Event Hub实体的),检查Endpoint、SharedAccessKeyName、SharedAccessKey是否复制正确,没有多余空格或字符。免费层命名空间需确认处于正常状态,未超出配额。修复代码逻辑错误
代码中存在明显错误:SendAsync传入了null的IEnumerable<EventData>,这会引发异常。同时需要检查TryAdd的返回值,确保事件成功加入批次:using EventDataBatch eventBatch = await producerClient.CreateBatchAsync(); if (!eventBatch.TryAdd(eventData)) { // 若当前批次无法容纳事件,发送现有批次后创建新批次 await producerClient.SendAsync(eventBatch); eventBatch = await producerClient.CreateBatchAsync(); if (!eventBatch.TryAdd(eventData)) { throw new InvalidOperationException("单个事件大小超过批次最大限制"); } } // 发送批次 await producerClient.SendAsync(eventBatch);免费层配额限制
Azure Event Hub免费层有吞吐量限制(每秒1MB、1000个事件),若循环发送速度过快可能触发限制。可在循环中添加await Task.Delay(100);降低发送频率,避免触发限流。
内容的提问来源于stack exchange,提问作者RK Tamil

