You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js调用Azure Event Hubs报错:EventHubProducerClient不是构造函数

解决Azure Event Hubs发送脚本的EventHubProducerClient is not a constructor错误

错误原因分析

出现该错误主要有两个核心原因:

  1. 依赖版本不兼容:你安装的@azure/event-hubs版本过低(v4及更早版本),这类版本中不存在EventHubProducerClient类,当时的生产者是通过EventHubClient创建的。
  2. 异步操作未正确处理:原代码中send()和close()都是异步方法,直接同步调用会导致客户端在消息发送完成前就被关闭,同时也会引发流程错误。

解决方案

步骤1:升级@azure/event-hubs到最新稳定版

执行以下命令更新依赖:

npm install @azure/event-hubs@latest

步骤2:修改脚本以正确处理异步流程并使用新版API

新版API要求使用异步函数包裹操作,并且推荐通过消息批次发送数据(Event Hubs的最佳实践),修改后的完整代码如下:

const { EventHubProducerClient } = require("@azure/event-hubs");

async function sendEventToHub() {
  // 初始化生产者客户端
  const producer = new EventHubProducerClient(
    "Endpoint=sb://auditblobevents.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=k9GhYMwABTBa6PuHKczIolE7FJeR0bOpQ+AEhEgMAY8=",
    "auditblobtopic"
  );

  try {
    // 创建消息批次
    const batch = await producer.createBatch();
    // 构造要发送的JSON数据
    const jsonRecord = {
      id: 1234567890,
      timestamp: new Date().toISOString(),
      message: "This is a JSON record."
    };
    // 将数据添加到批次中
    if (!batch.tryAdd({ body: JSON.stringify(jsonRecord) })) {
      throw new Error("消息大小超过批次限制");
    }
    // 发送批次
    await producer.sendBatch(batch);
    console.log("消息已成功发送到Event Hub");
  } catch (error) {
    console.error("发送消息失败:", error);
  } finally {
    // 确保客户端被关闭
    await producer.close();
  }
}

// 执行发送函数
sendEventToHub().catch(err => console.error(err));

若无法升级依赖的兼容方案(不推荐)

如果你因某些原因无法升级依赖,可使用旧版API的写法:

const { EventHubClient } = require("@azure/event-hubs");

async function sendEvent() {
  const client = EventHubClient.createFromConnectionString(
    "Endpoint=sb://auditblobevents.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=k9GhYMwABTBa6PuHKczIolE7FJeR0bOpQ+AEhEgMAY8=",
    "auditblobtopic"
  );
  const producer = client.createProducer();

  try {
    const jsonRecord = {
      id: 1234567890,
      timestamp: new Date().toISOString(),
      message: "This is a JSON record."
    };
    await producer.send({ body: JSON.stringify(jsonRecord) });
    console.log("消息发送成功");
  } catch (err) {
    console.error("发送失败:", err);
  } finally {
    await producer.close();
    await client.close();
  }
}

sendEvent().catch(err => console.error(err));

注意:旧版API已不再被官方推荐维护,建议优先选择升级依赖的方案。

内容的提问来源于stack exchange,提问作者Eugene Goldberg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 17:39:50