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

當您的函式首次啟用時,只會有 1 個該函式的執行個體。When your function is first enabled, there is only one instance of the function. 讓我們呼叫第一個函式Function_0實例。Let'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:

  • 不需要新的函式實例Function_0 : 能夠在函數調整邏輯生效之前處理所有1000事件。New function instances are not needed: Function_0 is able to process all 1,000 events before the Functions scaling logic take effect. 在此情況下, 所有1000訊息都會由Function_0處理。In this case, all 1,000 messages are processed by Function_0.

  • 再新增 1 個函式執行個體:如果函式調整邏輯判斷所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 個函式執行個體:如果函式調整邏輯判斷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.

當函式調整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. 當檢查指標成功時, 永遠不會再次抓取所有1000訊息。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.x 版Version 2.x

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

1.x 版Version 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.x 版Version 2.x

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

1.x 版Version 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.x 版Version 2.x

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

1.x 版Version 1.x

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

以下是 JavaScript 程式碼:Here's the JavaScript code:

module.exports = function (context, myEventHubMessage) {
    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.x 版Version 2.x

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

1.x 版Version 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 或可為 null 的值使用<選擇性的 T >。This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>.

觸發程序 - 屬性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 property 描述Description
typetype n/an/a 必須設為 eventHubTriggerMust be set to eventHubTrigger. 當您在 Azure 入口網站中建立觸發程序時,會自動設定此屬性。This property is set automatically when you create the trigger in the Azure portal.
directiondirection n/an/a 必須設為 inMust be set to in. 當您在 Azure 入口網站中建立觸發程序時,會自動設定此屬性。This property is set automatically when you create the trigger in the Azure portal.
namename n/an/a 代表函式程式碼中事件項目的變數名稱。The name of the variable that represents the event item in function code.
pathpath 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 取用者)。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/an/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 連接Connection 應用程式設定的名稱,其中包含事件中樞命名空間的連接字串。The name of an app setting that contains the connection string to the event hub's namespace. 按一下命名空間#create 的 [連接資訊] 按鈕 (而不是事件中樞本身), 來複製此連接字串。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.
pathpath 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/an/a 基礎 EventProcessorHost 將使用的預設 PrefetchCount。The default PrefetchCount that will be used by the underlying EventProcessorHost.
batchCheckpointFrequencybatchCheckpointFrequency 11 要在建立 EventHub 資料指標檢查點之前處理的事件批次數目。The number of event batches to process before creating an EventHub cursor checkpoint.

OutputOutput

使用事件中樞輸出繫結將事件寫入事件串流。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 property 描述Description
typetype n/an/a 必須設定為 "eventHub"。Must be set to "eventHub".
directiondirection n/an/a 必須設定為 "out"。Must be set to "out". 當您在 Azure 入口網站中建立繫結時,會自動設定此參數。This parameter is set automatically when you create the binding in the Azure portal.
namename n/an/a 函式程式碼中所使用的變數名稱,代表事件。The variable name used in function code that represents the event.
pathpath 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 連接Connection 應用程式設定的名稱,其中包含事件中樞命名空間的連接字串。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# 指令碼中,paramNamefunction.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.json 之 name 屬性中指定的值。<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/an/a 基礎 EventProcessorHost 將使用的預設 PrefetchCount。The default PrefetchCount that will be used by the underlying EventProcessorHost.
batchCheckpointFrequencybatchCheckpointFrequency 11 要在建立 EventHub 資料指標檢查點之前處理的事件批次數目。The number of event batches to process before creating an EventHub cursor checkpoint.

後續步驟Next steps