您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

Azure Functions 的 Azure 事件中心绑定Azure Event Hubs bindings for Azure Functions

本文介绍如何使用 Azure Functions 的 Azure 事件中心绑定。This article explains how to work with Azure Event Hubs bindings for Azure Functions. Azure Functions 支持事件中心的触发器和输出绑定。Azure Functions supports trigger and output bindings for Event Hubs.

此参考信息面向 Azure Functions 开发人员。This is reference information for Azure Functions developers. Azure Functions 的新手请从以下资源入手:If you're new to Azure Functions, start with the following resources:

包 - Functions 1.xPackages - Functions 1.x

对于 Azure Functions 版本 1.x,Microsoft.Azure.WebJobs.ServiceBus NuGet 包 2.x 版中提供了事件中心绑定。For Azure Functions version 1.x, the Event Hubs bindings are provided in the Microsoft.Azure.WebJobs.ServiceBus NuGet package, version 2.x. azure-webjobs-sdk GitHub 存储库中提供了此包的源代码。Source code for the package is in the azure-webjobs-sdk GitHub repository.

下表说明了如何在每个开发环境中添加对此绑定的支持。The following table tells how to add support for this binding in each development environment.

开发环境Development environment 添加支持To add support in
Functions 1.xFunctions 1.x
本地开发 - C# 类库Local development - C# class library 安装包Install the package
本地开发 - C# 脚本、JavaScript、F#Local development - C# script, JavaScript, F# 自动Automatic
门户开发Portal development 自动Automatic

包 - Functions 2.xPackages - Functions 2.x

对于 Functions 2.x,请使用 Microsoft.Azure.WebJobs.Extensions.EventHubs 包 3.x 版。For Functions 2.x, use the Microsoft.Azure.WebJobs.Extensions.EventHubs package, version 3.x. azure-webjobs-sdk GitHub 存储库中提供了此包的源代码。Source code for the package is in the azure-webjobs-sdk GitHub repository.

下表说明了如何在每个开发环境中添加对此绑定的支持。The following table tells how to add support for this binding in each development environment.

开发环境Development environment 添加支持To add support in
Functions 2.xFunctions 2.x
本地开发 - C# 类库Local development - C# class library 安装包Install the package
本地开发 - C# 脚本、JavaScript、F#、Java 和 PythonLocal development - C# script, JavaScript, F#, Java and Python 注册扩展Register the extension
门户开发Portal development 添加输出绑定时安装Install when adding output binding

若要了解如何更新门户中的现有绑定扩展而不必重新发布函数应用项目,请参阅更新扩展To learn how to update existing binding extensions in the portal without having to republish your function app project, see Update your extensions.

触发器Trigger

使用函数触发器来响应发送到事件中心事件流的事件。Use the function trigger to respond to an event sent to an event hub event stream. 若要设置触发器,必须具有基础事件中心的读取访问权限。You must have read access to the underlying event hub to set up the trigger. 触发函数时,传递给函数的消息充当字符串类型。When the function is triggered, the message passed to the function is typed as a string.

触发器 - 缩放Trigger - scaling

事件触发的函数的每个实例由单个 EventProcessorHost 实例提供支持。Each instance of an event triggered function is backed by a single EventProcessorHost instance. 触发器(由事件中心提供支持)确保只有一个 EventProcessorHost 实例能够在给定分区上获得租约。The trigger (powered by Event Hubs) ensures that only one EventProcessorHost instance can get a lease on a given partition.

例如,考虑如下所述的一个事件中心:For example, consider an Event Hub as follows:

  • 10 个分区10 partitions
  • 在所有分区之间平均分配 1000 个事件,每个分区中有 100 条消息1,000 events distributed evenly across all partitions, with 100 messages in each partition

首次启用函数时,只有一个函数实例。When your function is first enabled, there is only one instance of the function. 我们将第一个函数实例命名为 Function_0Let's call the first function instance Function_0. Function_0 函数具有单个 EventProcessorHost 实例,此实例在所有十个分区上都有租约。The Function_0 function has a single instance of EventProcessorHost that holds a lease on all ten partitions. 此实例从分区 0-9 读取事件。This instance is reading events from partitions 0-9. 从此时开始,将发生下列情况之一:From this point forward, one of the following happens:

  • 不需要新的函数实例:在 Functions 的缩放逻辑生效之前,Function_0 能够处理所有 1,000 个事件。New function instances are not needed: Function_0 is able to process all 1,000 events before the Functions scaling logic take effect. 在这种情况下,所有 1,000 条消息都由 Function_0 处理。In this case, all 1,000 messages are processed by Function_0.

  • 添加其他函数实例:如果 Functions 缩放逻辑确定 Function_0 的消息数超出了它的处理能力,则会创建新的函数应用实例 (Function_1)。An additional function instance is added: If the Functions scaling logic determines that Function_0 has more messages than it can process, a new function app instance (Function_1) is created. 此新函数也有一个关联的 EventProcessorHost 实例。This new function also has an associated instance of EventProcessorHost. 基础事件中心检测到新主机实例在尝试读取消息时,会在其主机实例之间对分区进行负载均衡。As the underlying Event Hubs detect that a new host instance is trying read messages, it load balances the partitions across the its host instances. 例如,可以将分区 0-4 分配给 Function_0,将分区 5-9 分配给 Function_1For example, partitions 0-4 may be assigned to Function_0 and partitions 5-9 to Function_1.

  • 额外添加 N 个函数实例:如果 Functions 缩放逻辑确定 Function_0Function_1 的消息数超出了它们的处理能力,则会创建新的 Functions_N 函数应用实例。N more function instances are added: If the Functions scaling logic determines that both Function_0 and Function_1 have more messages than they can process, new Functions_N function app instances are created. 会一直创建应用,直到 N 大于事件中心分区数为止。Apps are created to the point where N is greater than the number of event hub partitions. 在我们的示例中,事件中心再次对分区进行负载均衡,在本例中是在实例 Function_0...Functions_9 之间进行的。In our example, Event Hubs again load balances the partitions, in this case across the instances Function_0...Functions_9.

当 Functions 缩放时,N 实例是一个大于事件中心分区数的数字。When Functions scales, N instances is a number greater than the number of event hub partitions. 这样做是为了确保 EventProcessorHost 实例可供用来在其他实例释放锁时在分区上获取锁。This is done to ensure EventProcessorHost instances are available to obtain locks on partitions as they become available from other instances. 你只需为执行函数实例时使用的资源付费。You are only charged for the resources used when the function instance executes. 换句话说,不需要为过度预配的资源付费。In other words, you are not charged for this over-provisioning.

当所有函数执行都完成时(不管是否有错误),则会将检查点添加到关联的存储帐户。When all function execution completes (with or without errors), checkpoints are added to the associated storage account. 检查点设置成功后,永远不会再次检索所有 1,000 条消息。When check-pointing succeeds, all 1,000 messages are never retrieved again.

触发器 - 示例Trigger - example

参阅语言特定的示例:See the language-specific example:

触发器 - C# 示例Trigger - C# example

以下示例演示用于记录事件中心触发器消息正文的 C# 函数The following example shows a C# function that logs the message body of the event hub trigger.

[FunctionName("EventHubTriggerCSharp")]
public static void Run([EventHubTrigger("samples-workitems", Connection = "EventHubConnectionAppSetting")] string myEventHubMessage, ILogger log)
{
    log.LogInformation($"C# function triggered to process a message: {myEventHubMessage}");
}

若要在函数代码中访问事件元数据,请绑定到 EventData 对象(需要对 Microsoft.Azure.EventHubs 使用 using 语句)。To get access to event metadata in function code, bind to an EventData object (requires a using statement for Microsoft.Azure.EventHubs). 此外,还可以通过在方法签名中使用绑定表达式来访问相同的属性。You can also access the same properties by using binding expressions in the method signature. 以下示例演示了获取相同数据的两种方法:The following example shows both ways to get the same data:

[FunctionName("EventHubTriggerCSharp")]
public static void Run(
    [EventHubTrigger("samples-workitems", Connection = "EventHubConnectionAppSetting")] EventData myEventHubMessage,
    DateTime enqueuedTimeUtc,
    Int64 sequenceNumber,
    string offset,
    ILogger log)
{
    log.LogInformation($"Event: {Encoding.UTF8.GetString(myEventHubMessage.Body)}");
    // Metadata accessed by binding to EventData
    log.LogInformation($"EnqueuedTimeUtc={myEventHubMessage.SystemProperties.EnqueuedTimeUtc}");
    log.LogInformation($"SequenceNumber={myEventHubMessage.SystemProperties.SequenceNumber}");
    log.LogInformation($"Offset={myEventHubMessage.SystemProperties.Offset}");
    // Metadata accessed by using binding expressions in method parameters
    log.LogInformation($"EnqueuedTimeUtc={enqueuedTimeUtc}");
    log.LogInformation($"SequenceNumber={sequenceNumber}");
    log.LogInformation($"Offset={offset}");
}

若要成批接收事件,请将 stringEventData 设为数组。To receive events in a batch, make string or EventData an array.

备注

成批接收事件时,不能像上述示例那样使用 DateTime enqueuedTimeUtc 绑定到方法参数,且必须从每个 EventData 对象中接收这些事件When receiving in a batch you cannot bind to method parameters like in the above example with DateTime enqueuedTimeUtc and must receive these from each EventData object

[FunctionName("EventHubTriggerCSharp")]
public static void Run([EventHubTrigger("samples-workitems", Connection = "EventHubConnectionAppSetting")] EventData[] eventHubMessages, ILogger log)
{
    foreach (var message in eventHubMessages)
    {
        log.LogInformation($"C# function triggered to process a message: {Encoding.UTF8.GetString(message.Body)}");
        log.LogInformation($"EnqueuedTimeUtc={message.SystemProperties.EnqueuedTimeUtc}");
    }
}

触发器 - C# 脚本示例Trigger - C# script example

以下示例演示 function.json 文件中的一个事件中心触发器绑定以及使用该绑定的 C# 脚本函数The following example shows an event hub trigger binding in a function.json file and a C# script function that uses the binding. 该函数记录事件中心触发器的消息正文。The function logs the message body of the event hub trigger.

以下示例显示了 function.json 文件中的事件中心绑定数据。The following examples show Event Hubs binding data in the function.json file.

版本 2.xVersion 2.x

{
  "type": "eventHubTrigger",
  "name": "myEventHubMessage",
  "direction": "in",
  "eventHubName": "MyEventHub",
  "connection": "myEventHubReadConnectionAppSetting"
}

版本 1.xVersion 1.x

{
  "type": "eventHubTrigger",
  "name": "myEventHubMessage",
  "direction": "in",
  "path": "MyEventHub",
  "connection": "myEventHubReadConnectionAppSetting"
}

C# 脚本代码如下所示:Here's the C# script code:

using System;

public static void Run(string myEventHubMessage, TraceWriter log)
{
    log.Info($"C# function triggered to process a message: {myEventHubMessage}");
}

若要在函数代码中访问事件元数据,请绑定到 EventData 对象(需要对 Microsoft.Azure.EventHubs 使用 using 语句)。To get access to event metadata in function code, bind to an EventData object (requires a using statement for Microsoft.Azure.EventHubs). 此外,还可以通过在方法签名中使用绑定表达式来访问相同的属性。You can also access the same properties by using binding expressions in the method signature. 以下示例演示了获取相同数据的两种方法:The following example shows both ways to get the same data:

#r "Microsoft.Azure.EventHubs"

using System.Text;
using System;
using Microsoft.ServiceBus.Messaging;
using Microsoft.Azure.EventHubs;

public static void Run(EventData myEventHubMessage,
    DateTime enqueuedTimeUtc,
    Int64 sequenceNumber,
    string offset,
    TraceWriter log)
{
    log.Info($"Event: {Encoding.UTF8.GetString(myEventHubMessage.Body)}");
    log.Info($"EnqueuedTimeUtc={myEventHubMessage.SystemProperties.EnqueuedTimeUtc}");
    log.Info($"SequenceNumber={myEventHubMessage.SystemProperties.SequenceNumber}");
    log.Info($"Offset={myEventHubMessage.SystemProperties.Offset}");

    // Metadata accessed by using binding expressions
    log.Info($"EnqueuedTimeUtc={enqueuedTimeUtc}");
    log.Info($"SequenceNumber={sequenceNumber}");
    log.Info($"Offset={offset}");
}

若要成批接收事件,请将 stringEventData 设为数组:To receive events in a batch, make string or EventData an array:

public static void Run(string[] eventHubMessages, TraceWriter log)
{
    foreach (var message in eventHubMessages)
    {
        log.Info($"C# function triggered to process a message: {message}");
    }
}

触发器 - F# 示例Trigger - F# example

以下示例演示 function.json 文件中的一个事件中心触发器绑定以及使用该绑定的 F# 函数The following example shows an event hub trigger binding in a function.json file and an F# function that uses the binding. 该函数记录事件中心触发器的消息正文。The function logs the message body of the event hub trigger.

以下示例显示了 function.json 文件中的事件中心绑定数据。The following examples show Event Hubs binding data in the function.json file.

版本 2.xVersion 2.x

{
  "type": "eventHubTrigger",
  "name": "myEventHubMessage",
  "direction": "in",
  "eventHubName": "MyEventHub",
  "connection": "myEventHubReadConnectionAppSetting"
}

版本 1.xVersion 1.x

{
  "type": "eventHubTrigger",
  "name": "myEventHubMessage",
  "direction": "in",
  "path": "MyEventHub",
  "connection": "myEventHubReadConnectionAppSetting"
}

F# 代码如下所示:Here's the F# code:

let Run(myEventHubMessage: string, log: TraceWriter) =
    log.Log(sprintf "F# eventhub trigger function processed work item: %s" myEventHubMessage)

触发器 - JavaScript 示例Trigger - JavaScript example

以下示例演示 function.json 文件中的一个事件中心触发器绑定以及使用该绑定的 JavaScript 函数The following example shows an event hub trigger binding in a function.json file and a JavaScript function that uses the binding. 此函数将读取事件元数据并记录消息。The function reads event metadata and logs the message.

以下示例显示了 function.json 文件中的事件中心绑定数据。The following examples show Event Hubs binding data in the function.json file.

版本 2.xVersion 2.x

{
  "type": "eventHubTrigger",
  "name": "myEventHubMessage",
  "direction": "in",
  "eventHubName": "MyEventHub",
  "connection": "myEventHubReadConnectionAppSetting"
}

版本 1.xVersion 1.x

{
  "type": "eventHubTrigger",
  "name": "myEventHubMessage",
  "direction": "in",
  "path": "MyEventHub",
  "connection": "myEventHubReadConnectionAppSetting"
}

JavaScript 代码如下所示:Here's the JavaScript code:

module.exports = function (context, eventHubMessage) {
    context.log('Function triggered to process a message: ', myEventHubMessage);
    context.log('EnqueuedTimeUtc =', context.bindingData.enqueuedTimeUtc);
    context.log('SequenceNumber =', context.bindingData.sequenceNumber);
    context.log('Offset =', context.bindingData.offset);

    context.done();
};

若要批量接收事件,请将 function.json 文件中的 cardinality 设为 many,如以下示例所示。To receive events in a batch, set cardinality to many in the function.json file, as shown in the following examples.

版本 2.xVersion 2.x

{
  "type": "eventHubTrigger",
  "name": "eventHubMessages",
  "direction": "in",
  "eventHubName": "MyEventHub",
  "cardinality": "many",
  "connection": "myEventHubReadConnectionAppSetting"
}

版本 1.xVersion 1.x

{
  "type": "eventHubTrigger",
  "name": "eventHubMessages",
  "direction": "in",
  "path": "MyEventHub",
  "cardinality": "many",
  "connection": "myEventHubReadConnectionAppSetting"
}

JavaScript 代码如下所示:Here's the JavaScript code:

module.exports = function (context, eventHubMessages) {
    context.log(`JavaScript eventhub trigger function called for message array ${eventHubMessages}`);

    eventHubMessages.forEach((message, index) => {
        context.log(`Processed message ${message}`);
        context.log(`EnqueuedTimeUtc = ${context.bindingData.enqueuedTimeUtcArray[index]}`);
        context.log(`SequenceNumber = ${context.bindingData.sequenceNumberArray[index]}`);
        context.log(`Offset = ${context.bindingData.offsetArray[index]}`);
    });

    context.done();
};

触发器 - Python 示例Trigger - Python example

以下示例演示 function.json 文件中的事件中心触发器绑定以及使用该绑定的 Python 函数The following example shows an event hub trigger binding in a function.json file and a Python function that uses the binding. 此函数将读取事件元数据并记录消息。The function reads event metadata and logs the message.

以下示例显示了 function.json 文件中的事件中心绑定数据。The following examples show Event Hubs binding data in the function.json file.

{
  "type": "eventHubTrigger",
  "name": "event",
  "direction": "in",
  "eventHubName": "MyEventHub",
  "connection": "myEventHubReadConnectionAppSetting"
}

下面是 Python 代码:Here's the Python code:

import logging
import azure.functions as func

def main(event: func.EventHubEvent):
    logging.info('Function triggered to process a message: ', event.get_body())
    logging.info('  EnqueuedTimeUtc =', event.enqueued_time)
    logging.info('  SequenceNumber =', event.sequence_number)
    logging.info('  Offset =', event.offset)

触发器 - Java 示例Trigger - Java example

以下示例演示 function.json 文件中的一个事件中心触发器绑定以及使用该绑定的 Java 函数The following example shows an Event Hub trigger binding in a function.json file and an Java function that uses the binding. 该函数记录事件中心触发器的消息正文。The function logs the message body of the Event Hub trigger.

{
  "type": "eventHubTrigger",
  "name": "msg",
  "direction": "in",
  "eventHubName": "myeventhubname",
  "connection": "myEventHubReadConnectionAppSetting"
}
@FunctionName("ehprocessor")
public void eventHubProcessor(
  @EventHubTrigger(name = "msg",
                  eventHubName = "myeventhubname",
                  connection = "myconnvarname") String message,
       final ExecutionContext context )
       {
          context.getLogger().info(message);
 }

Java 函数运行时库中,对其值来自事件中心的参数使用 EventHubTrigger 注释。In the Java functions runtime library, use the EventHubTrigger annotation on parameters whose value would come from Event Hub. 带有这些注释的参数会导致函数在事件到达时运行。Parameters with these annotations cause the function to run when an event arrives. 可以将此注释与本机 Java 类型、POJO 或使用了 Optional 的可为 null 的值一起使用。This annotation can be used with native Java types, POJOs, or nullable values using Optional.

触发器 - 特性Trigger - attributes

C# 类库中,使用 EventHubTriggerAttribute 特性。In C# class libraries, use the EventHubTriggerAttribute attribute.

该特性的构造函数使用事件中心的名称、使用者组的名称和包含连接字符串的应用设置的名称。The attribute's constructor takes the name of the event hub, the name of the consumer group, and the name of an app setting that contains the connection string. 有关这些设置的详细信息,请参阅触发器配置部分For more information about these settings, see the trigger configuration section. 下面是 EventHubTriggerAttribute 特性的示例:Here's an EventHubTriggerAttribute attribute example:

[FunctionName("EventHubTriggerCSharp")]
public static void Run([EventHubTrigger("samples-workitems", Connection = "EventHubConnectionAppSetting")] string myEventHubMessage, ILogger log)
{
    ...
}

有关完整示例,请参阅触发器 - C# 示例For a complete example, see Trigger - C# example.

触发器 - 配置Trigger - configuration

下表解释了在 function.json 文件和 EventHubTrigger 特性中设置的绑定配置属性。The following table explains the binding configuration properties that you set in the function.json file and the EventHubTrigger attribute.

function.json 属性function.json property Attribute 属性Attribute property 说明Description
typetype 不适用n/a 必须设置为 eventHubTriggerMust be set to eventHubTrigger. 在 Azure 门户中创建触发器时,会自动设置此属性。This property is set automatically when you create the trigger in the Azure portal.
directiondirection 不适用n/a 必须设置为 inMust be set to in. 在 Azure 门户中创建触发器时,会自动设置此属性。This property is set automatically when you create the trigger in the Azure portal.
namename 不适用n/a 在函数代码中表示事件项的变量的名称。The name of the variable that represents the event item in function code.
路径path EventHubNameEventHubName 仅适用于 Functions 1.x。Functions 1.x only. 事件中心的名称。The name of the event hub. 当事件中心名称也出现在连接字符串中时,该值会在运行时覆盖此属性。When the event hub name is also present in the connection string, that value overrides this property at runtime.
eventHubNameeventHubName EventHubNameEventHubName 仅适用于 Functions 2.x。Functions 2.x only. 事件中心的名称。The name of the event hub. 当事件中心名称也出现在连接字符串中时,该值会在运行时覆盖此属性。When the event hub name is also present in the connection string, that value overrides this property at runtime.
consumerGroupconsumerGroup ConsumerGroupConsumerGroup 一个可选属性,用于设置使用者组#event-consumers),该组用于订阅事件中心的事件。An optional property that sets the consumer group#event-consumers) used to subscribe to events in the hub. 如果将其省略,则会使用 $Default 使用者组。If omitted, the $Default consumer group is used.
基数cardinality 不适用n/a 适用于 JavaScript。For Javascript. 设为 many 以启用批处理。Set to many in order to enable batching. 如果省略或设为 one,将向函数传递一条消息。If omitted or set to one, single message passed to function.
连接connection ConnectionConnection 应用设置的名称,该名称中包含事件中心命名空间的连接字符串。The name of an app setting that contains the connection string to the event hub's namespace. 单击 命名空间#create-an-event-hubs-namespace)(而不是事件中心本身)的“连接信息”按钮,以复制此连接字符串。Copy this connection string by clicking the Connection Information button for the namespace#create-an-event-hubs-namespace), not the event hub itself. 此连接字符串必须至少具有读取权限才可激活触发器。This connection string must have at least read permissions to activate the trigger.
路径path EventHubNameEventHubName 事件中心的名称。The name of the event hub. 可以通过应用设置 %eventHubName% 引用Can be referenced via app settings %eventHubName%

在本地进行开发时,应用设置将取 local.settings.json 文件的值。When you're developing locally, app settings go into the local.settings.json file.

触发器 - 事件元数据Trigger - event metadata

事件中心触发器提供了几个元数据属性The Event Hubs trigger provides several metadata properties. 这些属性可在其他绑定中用作绑定表达式的一部分,或者用作代码中的参数。These properties can be used as part of binding expressions in other bindings or as parameters in your code. 以下是 EventData 类的属性。These are properties of the EventData class.

属性Property TypeType 描述Description
PartitionContext PartitionContextPartitionContext PartitionContext 实例。The PartitionContext instance.
EnqueuedTimeUtc DateTime 排队时间 (UTC)。The enqueued time in UTC.
Offset string 数据相对于事件中心分区流的偏移量。The offset of the data relative to the Event Hub partition stream. 偏移量是事件中心流中的事件的标记或标识符。The offset is a marker or identifier for an event within the Event Hubs stream. 该标识符在事件中心流的分区中是惟一的。The identifier is unique within a partition of the Event Hubs stream.
PartitionKey string 事件数据应该发送到的分区。The partition to which event data should be sent.
Properties IDictionary<String,Object> 事件数据的用户属性。The user properties of the event data.
SequenceNumber Int64 事件的逻辑序列号。The logical sequence number of the event.
SystemProperties IDictionary<String,Object> 系统属性,包括事件数据。The system properties, including the event data.

请参阅在本文的前面部分使用这些属性的代码示例See code examples that use these properties earlier in this article.

触发器 - host.json 属性Trigger - host.json properties

host.json 文件包含控制事件中心触发器行为的设置。The host.json file contains settings that control Event Hubs trigger behavior.

{
    "eventHub": {
      "maxBatchSize": 64,
      "prefetchCount": 256,
      "batchCheckpointFrequency": 1
    }
}
属性Property 默认Default 描述Description
maxBatchSizemaxBatchSize 6464 每个接收循环收到的最大事件计数。The maximum event count received per receive loop.
prefetchCountprefetchCount 不适用n/a 基础 EventProcessorHost 将要使用的默认 PrefetchCount。The default PrefetchCount that will be used by the underlying EventProcessorHost.
batchCheckpointFrequencybatchCheckpointFrequency 1 创建 EventHub 游标检查点之前要处理的事件批数。The number of event batches to process before creating an EventHub cursor checkpoint.

输出Output

使用事件中心输出绑定将事件写入到事件流。Use the Event Hubs output binding to write events to an event stream. 必须具有事件中心的发送权限才可将事件写入到其中。You must have send permission to an event hub to write events to it.

请确保所需的包引用已准备好:Functions 1.x 或 Functions 2.xEnsure the required package references are in place: Functions 1.x or Functions 2.x

输出 - 示例Output - example

参阅语言特定的示例:See the language-specific example:

输出 - C# 示例Output - C# example

以下示例演示使用方法返回值作为输出将消息写入到事件中心的 C# 函数The following example shows a C# function that writes a message to an event hub, using the method return value as the output:

[FunctionName("EventHubOutput")]
[return: EventHub("outputEventHubMessage", Connection = "EventHubConnectionAppSetting")]
public static string Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, ILogger log)
{
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    return $"{DateTime.Now}";
}

下面的示例演示如何使用IAsyncCollector接口以便将发送一批消息。The following sample shows how to use the IAsyncCollector interface to send a batch of messages. 所处理的消息来自一个事件中心,并且将结果发送到另一个事件中心时,此方案中很常见。This scenario is common when you are processing messages coming from one Event Hub and sending the result to another Event Hub.

[FunctionName("EH2EH")]
public static async Task Run(
    [EventHubTrigger("source", Connection = "EventHubConnectionAppSetting")] EventData[] events,
    [EventHub("dest", Connection = "EventHubConnectionAppSetting")]IAsyncCollector<string> outputEvents,
    ILogger log)
{
    foreach (EventData eventData in events)
    {
        // do some processing:
        var myProcessedEvent = DoSomething(eventData);

        // then send the message
        await outputEvents.AddAsync(JsonConvert.SerializeObject(myProcessedEvent));
    }
}

输出 - C# 脚本示例Output - C# script example

以下示例演示 function.json 文件中的一个事件中心触发器绑定以及使用该绑定的 C# 脚本函数The following example shows an event hub trigger binding in a function.json file and a C# script function that uses the binding. 该函数将消息写入事件中心。The function writes a message to an event hub.

以下示例显示了 function.json 文件中的事件中心绑定数据。The following examples show Event Hubs binding data in the function.json file. 第一个示例适用于 Functions 2.x,第二个示例适用于 Functions 1.x。The first example is for Functions 2.x, and the second one is for Functions 1.x.

{
    "type": "eventHub",
    "name": "outputEventHubMessage",
    "eventHubName": "myeventhub",
    "connection": "MyEventHubSendAppSetting",
    "direction": "out"
}
{
    "type": "eventHub",
    "name": "outputEventHubMessage",
    "path": "myeventhub",
    "connection": "MyEventHubSendAppSetting",
    "direction": "out"
}

下面是可创建一条消息的 C# 脚本代码:Here's C# script code that creates one message:

using System;
using Microsoft.Extensions.Logging;

public static void Run(TimerInfo myTimer, out string outputEventHubMessage, ILogger log)
{
    String msg = $"TimerTriggerCSharp1 executed at: {DateTime.Now}";
    log.LogInformation(msg);   
    outputEventHubMessage = msg;
}

下面是可创建多条消息的 C# 脚本代码:Here's C# script code that creates multiple messages:

public static void Run(TimerInfo myTimer, ICollector<string> outputEventHubMessage, ILogger log)
{
    string message = $"Message created at: {DateTime.Now}";
    log.LogInformation(message);
    outputEventHubMessage.Add("1 " + message);
    outputEventHubMessage.Add("2 " + message);
}

输出 - F# 示例Output - F# example

以下示例演示 function.json 文件中的一个事件中心触发器绑定以及使用该绑定的 F# 函数The following example shows an event hub trigger binding in a function.json file and an F# function that uses the binding. 该函数将消息写入事件中心。The function writes a message to an event hub.

以下示例显示了 function.json 文件中的事件中心绑定数据。The following examples show Event Hubs binding data in the function.json file. 第一个示例适用于 Functions 2.x,第二个示例适用于 Functions 1.x。The first example is for Functions 2.x, and the second one is for Functions 1.x.

{
    "type": "eventHub",
    "name": "outputEventHubMessage",
    "eventHubName": "myeventhub",
    "connection": "MyEventHubSendAppSetting",
    "direction": "out"
}
{
    "type": "eventHub",
    "name": "outputEventHubMessage",
    "path": "myeventhub",
    "connection": "MyEventHubSendAppSetting",
    "direction": "out"
}

F# 代码如下所示:Here's the F# code:

let Run(myTimer: TimerInfo, outputEventHubMessage: byref<string>, log: ILogger) =
    let msg = sprintf "TimerTriggerFSharp1 executed at: %s" DateTime.Now.ToString()
    log.LogInformation(msg);
    outputEventHubMessage <- msg;

输出 - JavaScript 示例Output - JavaScript example

以下示例演示 function.json 文件中的一个事件中心触发器绑定以及使用该绑定的 JavaScript 函数The following example shows an event hub trigger binding in a function.json file and a JavaScript function that uses the binding. 该函数将消息写入事件中心。The function writes a message to an event hub.

以下示例显示了 function.json 文件中的事件中心绑定数据。The following examples show Event Hubs binding data in the function.json file. 第一个示例适用于 Functions 2.x,第二个示例适用于 Functions 1.x。The first example is for Functions 2.x, and the second one is for Functions 1.x.

{
    "type": "eventHub",
    "name": "outputEventHubMessage",
    "eventHubName": "myeventhub",
    "connection": "MyEventHubSendAppSetting",
    "direction": "out"
}
{
    "type": "eventHub",
    "name": "outputEventHubMessage",
    "path": "myeventhub",
    "connection": "MyEventHubSendAppSetting",
    "direction": "out"
}

下面是可发送一条消息的 JavaScript 代码:Here's JavaScript code that sends a single message:

module.exports = function (context, myTimer) {
    var timeStamp = new Date().toISOString();
    context.log('Message created at: ', timeStamp);   
    context.bindings.outputEventHubMessage = "Message created at: " + timeStamp;
    context.done();
};

下面是可发送多条消息的 JavaScript 代码:Here's JavaScript code that sends multiple messages:

module.exports = function(context) {
    var timeStamp = new Date().toISOString();
    var message = 'Message created at: ' + timeStamp;

    context.bindings.outputEventHubMessage = [];

    context.bindings.outputEventHubMessage.push("1 " + message);
    context.bindings.outputEventHubMessage.push("2 " + message);
    context.done();
};

输出 - Python 示例Output - Python example

以下示例演示 function.json 文件中的事件中心触发器绑定以及使用该绑定的 Python 函数The following example shows an event hub trigger binding in a function.json file and a Python function that uses the binding. 该函数将消息写入事件中心。The function writes a message to an event hub.

以下示例显示了 function.json 文件中的事件中心绑定数据。The following examples show Event Hubs binding data in the function.json file.

{
    "type": "eventHub",
    "name": "$return",
    "eventHubName": "myeventhub",
    "connection": "MyEventHubSendAppSetting",
    "direction": "out"
}

下面是可发送一条消息的 Python 代码:Here's Python code that sends a single message:

import datetime
import logging
import azure.functions as func

def main(timer: func.TimerRequest) -> str:
    timestamp = datetime.datetime.utcnow()
    logging.info('Message created at: %s', timestamp);   
    return 'Message created at: {}'.format(timestamp)

输出 - Java 示例Output - Java example

以下示例演示一个将包含当前时间的消息写入到事件中心的 Java 函数。The following example shows a Java function that writes a message contianing the current time to an Event Hub.

@}FunctionName("sendTime")
@EventHubOutput(name = "event", eventHubName = "samples-workitems", connection = "AzureEventHubConnection")
public String sendTime(
   @TimerTrigger(name = "sendTimeTrigger", schedule = "0 *&#47;5 * * * *") String timerInfo)  {
     return LocalDateTime.now().toString();
 }

Java 函数运行时库中,对其值将被发布到事件中心的参数使用 @EventHubOutput 注释。In the Java functions runtime library, use the @EventHubOutput annotation on parameters whose value would be published to Event Hub. 此参数应为 OutputBinding<T> 类型,其中 T 是 POJO 或任何本机 Java 类型。The parameter should be of type OutputBinding<T> , where T is a POJO or any native Java type.

输出 - 特性Output - attributes

对于 C# 类库,使用 EventHubAttribute 特性。For C# class libraries, use the EventHubAttribute attribute.

该特性的构造函数使用事件中心的名称和包含连接字符串的应用设置的名称。The attribute's constructor takes the name of the event hub and the name of an app setting that contains the connection string. 有关这些设置的详细信息,请参阅输出 - 配置For more information about these settings, see Output - configuration. 下面是 EventHub 特性的示例:Here's an EventHub attribute example:

[FunctionName("EventHubOutput")]
[return: EventHub("outputEventHubMessage", Connection = "EventHubConnectionAppSetting")]
public static string Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, ILogger log)
{
    ...
}

有关完整示例,请参阅输出 - C# 示例For a complete example, see Output - C# example.

输出 - 配置Output - configuration

下表解释了在 function.json 文件和 EventHub 特性中设置的绑定配置属性。The following table explains the binding configuration properties that you set in the function.json file and the EventHub attribute.

function.json 属性function.json property Attribute 属性Attribute property 说明Description
typetype 不适用n/a 必须设置为“eventHub”。Must be set to "eventHub".
directiondirection 不适用n/a 必须设置为“out”。Must be set to "out". 在 Azure 门户中创建绑定时,会自动设置该参数。This parameter is set automatically when you create the binding in the Azure portal.
namename 不适用n/a 函数代码中使用的表示事件的变量名称。The variable name used in function code that represents the event.
路径path EventHubNameEventHubName 仅适用于 Functions 1.x。Functions 1.x only. 事件中心的名称。The name of the event hub. 当事件中心名称也出现在连接字符串中时,该值会在运行时覆盖此属性。When the event hub name is also present in the connection string, that value overrides this property at runtime.
eventHubNameeventHubName EventHubNameEventHubName 仅适用于 Functions 2.x。Functions 2.x only. 事件中心的名称。The name of the event hub. 当事件中心名称也出现在连接字符串中时,该值会在运行时覆盖此属性。When the event hub name is also present in the connection string, that value overrides this property at runtime.
连接connection ConnectionConnection 应用设置的名称,该名称中包含事件中心命名空间的连接字符串。The name of an app setting that contains the connection string to the event hub's namespace. 单击 命名空间 (而不是事件中心本身)的“连接信息”按钮,以复制此连接字符串。Copy this connection string by clicking the Connection Information button for the namespace, not the event hub itself. 此连接字符串必须具有发送权限才可将消息发送到事件流。This connection string must have send permissions to send the message to the event stream.

在本地进行开发时,应用设置将取 local.settings.json 文件的值。When you're developing locally, app settings go into the local.settings.json file.

输出 - 用法Output - usage

在 C# 和 C# 脚本中,可以使用 out string paramName 等方法参数发送消息。In C# and C# script, send messages by using a method parameter such as out string paramName. 在 C# 脚本中,paramName 是在 function.jsonname 属性中指定的值。In C# script, paramName is the value specified in the name property of function.json. 若要编写多条消息,可以使用 ICollector<string>IAsyncCollector<string> 代替 out stringTo write multiple messages, you can use ICollector<string> or IAsyncCollector<string> in place of out string.

在 JavaScript 中,通过使用 context.bindings.<name> 访问输出事件。In JavaScript, access the output event by using context.bindings.<name>. <name> 是在 function.jsonname 属性中指定的值。<name> is the value specified in the name property of function.json.

异常和返回代码Exceptions and return codes

绑定Binding 参考Reference
事件中心Event Hub 操作指南Operations Guide

host.json 设置host.json settings

本部分介绍版本 2.x 中可用于此绑定的全局配置设置。This section describes the global configuration settings available for this binding in version 2.x. 下面的示例 host.json 文件仅包含此绑定的 2.x 版本设置。The example host.json file below contains only the version 2.x settings for this binding. 有关版本 2.x 中的全局配置设置的详细信息,请参阅 Azure Functions 版本 2.x 的 host.json 参考For more information about global configuration settings in version 2.x, see host.json reference for Azure Functions version 2.x.

备注

有关 Functions 1.x 中 host.json 的参考,请参阅 Azure Functions 1.x 的 host.json 参考For a reference of host.json in Functions 1.x, see host.json reference for Azure Functions 1.x.

{
    "version": "2.0",
    "extensions": {
        "eventHubs": {
            "batchCheckpointFrequency": 5,
            "eventProcessorOptions": {
                "maxBatchSize": 256,
                "prefetchCount": 512
            }
        }
    }
}  
属性Property 默认Default 描述Description
maxBatchSizemaxBatchSize 6464 每个接收循环收到的最大事件计数。The maximum event count received per receive loop.
prefetchCountprefetchCount 不适用n/a 基础 EventProcessorHost 将要使用的默认 PrefetchCount。The default PrefetchCount that will be used by the underlying EventProcessorHost.
batchCheckpointFrequencybatchCheckpointFrequency 1 创建 EventHub 游标检查点之前要处理的事件批数。The number of event batches to process before creating an EventHub cursor checkpoint.

后续步骤Next steps