本文介绍如何使用 Azure Functions 的 Azure 事件中心绑定。 Azure Functions 支持事件中心的触发器和输出绑定。
有关设置和配置详细信息,请参阅概述。
使用事件中心输出绑定将事件写入到事件流。 必须具有事件中心的发送权限才可将事件写入到其中。
在尝试实现输出绑定之前,请确保所需的包引用已准备就绪。
重要
本文使用选项卡来支持多个版本的 Node.js 编程模型。 v4 模型已正式发布,旨在为 JavaScript 和 TypeScript 开发人员提供更为灵活和直观的体验。 有关 v4 模型工作原理的更多详细信息,请参阅 Azure Functions Node.js 开发人员指南。 要详细了解 v3 和 v4 之间的差异,请参阅迁移指南。
Azure Functions 支持两种 Python 编程模型。 定义绑定的方式取决于选择的编程模型。
使用 Python v2 编程模型,可以直接在 Python 函数代码中使用修饰器定义绑定。 有关详细信息,请参阅 Python 开发人员指南。
本文同时支持两个编程模型。
示例
以下示例显示了使用方法返回值作为输出将消息字符串写入到事件中心的 C# 函数:
[Function(nameof(EventHubFunction))]
[FixedDelayRetry(5, "00:00:10")]
[EventHubOutput("dest", Connection = "EventHubConnection")]
public string EventHubFunction(
[EventHubTrigger("src", Connection = "EventHubConnection")] string[] input,
FunctionContext context)
{
_logger.LogInformation("First Event Hubs triggered message: {msg}", input[0]);
var message = $"Output message created at {DateTime.Now}";
return message;
}
以下示例显示计时器触发的 TypeScript 函数,该函数将一条消息发送到事件中心:
import { app, InvocationContext, output, Timer } from '@azure/functions';
export async function timerTrigger1(myTimer: Timer, context: InvocationContext): Promise<string> {
const timeStamp = new Date().toISOString();
return `Message created at: ${timeStamp}`;
}
app.timer('timerTrigger1', {
schedule: '0 */5 * * * *',
return: output.eventHub({
eventHubName: 'myeventhub',
connection: 'MyEventHubSendAppSetting',
}),
handler: timerTrigger1,
});
若要输出多条消息,请返回一个数组而不是单个对象。 例如:
import { app, InvocationContext, output, Timer } from '@azure/functions';
export async function timerTrigger1(myTimer: Timer, context: InvocationContext): Promise<string[]> {
// <displayInDocs>
const timeStamp = new Date().toISOString();
const message = `Message created at: ${timeStamp}`;
return [`1: ${message}`, `2: ${message}`];
// </displayInDocs>
}
app.timer('timerTrigger1', {
schedule: '0 */5 * * * *',
return: output.eventHub({
eventHubName: 'myeventhub',
connection: 'MyEventHubSendAppSetting',
}),
handler: timerTrigger1,
});
以下示例显示计时器触发的 JavaScript 函数,该函数将一条消息发送到事件中心:
const { app, output } = require('@azure/functions');
const eventHubOutput = output.eventHub({
eventHubName: 'myeventhub',
connection: 'MyEventHubSendAppSetting',
});
app.timer('timerTrigger1', {
schedule: '0 */5 * * * *',
return: eventHubOutput,
handler: (myTimer, context) => {
const timeStamp = new Date().toISOString();
return `Message created at: ${timeStamp}`;
},
});
若要输出多条消息,请返回一个数组而不是单个对象。 例如:
const { app, output } = require('@azure/functions');
const eventHubOutput = output.eventHub({
eventHubName: 'myeventhub',
connection: 'MyEventHubSendAppSetting',
});
app.timer('timerTrigger1', {
schedule: '0 */5 * * * *',
return: eventHubOutput,
handler: (myTimer, context) => {
// <displayInDocs>
const timeStamp = new Date().toISOString();
const message = `Message created at: ${timeStamp}`;
return [`1: ${message}`, `2: ${message}`];
// </displayInDocs>
},
});
完整的 PowerShell 示例待定。
以下示例演示了事件中心触发器绑定以及使用该绑定的 Python 函数。 该函数将消息写入事件中心。 该示例取决于使用的是 v1 还是 v2 Python 编程模型。
import logging
import azure.functions as func
app = func.FunctionApp()
@app.function_name(name="eventhub_output")
@app.route(route="eventhub_output")
@app.event_hub_output(arg_name="event",
event_hub_name="<EVENT_HUB_NAME>",
connection="<CONNECTION_SETTING>")
def eventhub_output(req: func.HttpRequest, event: func.Out[str]):
body = req.get_body()
if body is not None:
event.set(body.decode('utf-8'))
else:
logging.info('req body is none')
return 'ok'
下面是可发送多条消息的 Python 代码:
import logging
import azure.functions as func
from typing import List
app = func.FunctionApp()
@app.function_name(name="eventhub_output")
@app.route(route="eventhub_output")
@app.event_hub_output(arg_name="event",
event_hub_name="<EVENT_HUB_NAME>",
connection="<CONNECTION_SETTING>")
def eventhub_output(req: func.HttpRequest, event: func.Out[List[str]]) -> func.HttpResponse:
my_messages=["message1", "message2","message3"]
event.set(my_messages)
return func.HttpResponse(f"Messages sent")
以下示例演示一个 Java 函数,该函数将包含当前时间的消息写入到事件中心。
@FunctionName("sendTime")
@EventHubOutput(name = "event", eventHubName = "samples-workitems", connection = "AzureEventHubConnection")
public String sendTime(
@TimerTrigger(name = "sendTimeTrigger", schedule = "0 */5 * * * *") String timerInfo) {
return LocalDateTime.now().toString();
}
在 Java 函数运行时库中,会对其值被发布到事件中心的参数使用 @EventHubOutput 注释。 此参数应为 OutputBinding<T> 类型,其中 T 是 POJO 或任何本机 Java 类型。
修饰符
仅适用于 Python v2 编程模型。
对于使用修饰器定义的 Python v2 函数,支持 event_hub_output 的以下属性:
| properties | 说明 |
|---|---|
arg_name |
函数代码中使用的表示事件的变量名称。 |
event_hub_name |
事件中心的名称。 当事件中心名称也出现在连接字符串中时,该值会在运行时覆盖此属性。 |
connection |
指定如何连接到事件中心的应用设置或设置集合的名称。 若要了解详细信息,请参阅连接。 |
对于使用 function.json 定义的 Python 函数,请参阅“配置”部分。
配置
仅适用于 Python v1 编程模型。
下表说明了在 function.json 文件中设置的绑定配置属性,这些属性因运行时版本而异。
在本地开发时,需要将应用程序设置添加到 集合中的 Values中。
使用情况
事件中心输出绑定支持的参数类型取决于所用的 Functions 运行时版本、扩展包版本以及 C# 模态。
如果希望函数写入单个事件,事件中心输出绑定可以绑定到以下类型:
| 类型 | 说明 |
|---|---|
string |
字符串形式的事件。 当事件为简单文本时使用。 |
byte[] |
事件的字节数。 |
| JSON 可序列化类型 | 表示事件的对象。 函数尝试将普通的旧 CLR 对象 (POCO) 类型序列化为 JSON 数据。 |
如果希望函数写入多个事件,事件中心输出绑定可以绑定到以下类型:
| 类型 | 说明 |
|---|---|
T[],其中 T 是单事件类型之一 |
包含多个事件的数组。 每个条目表示一个事件。 |
对于其他输出方案,请直接从 Azure.Messaging.EventHubs 创建和使用 EventHubProducerClient 和其他类型。 有关使用依赖项注入从 Azure SDK 创建客户端类型的示例,请参阅 “注册 Azure 客户端 ”。
有两个选项可通过使用 EventHubOutput 注释从函数输出事件中心消息:
返回值:通过将注释应用于函数本身,函数的返回值将持久保存为事件中心消息。
命令性:若要显式设置消息值,请将注释应用于
OutputBinding<T>类型的特定参数,其中T是 POJO 或任何本机 Java 类型。 使用此配置时,向setValue方法传递某值会将该值持久保存为事件中心消息。
完整的 PowerShell 示例待定。
有两个选项可用于从函数中输出事件中心消息:
返回值:将 function.json 中的
name属性 设置为 。 使用此配置时,函数的返回值将作为事件中心消息保留。
输出函数参数必须定义为 func.Out[func.EventHubEvent] 或 func.Out[List[func.EventHubEvent]]。 有关详细信息,请参阅输出示例。
连接
该 connection 属性在应用设置中被设置为键,返回函数运行时用于连接包含扩展所用事件枢纽的事件枢纽命名空间的值。 连接属性设置的值取决于连接类型:
-
管理身份连接:该
connection属性是由<CONNECTION_NAME_PREFIX>一组设置共享的,这些设置共同定义了基于身份的命名空间连接。 更多信息请参见 定义身份连接。 -
密钥保管库 引用:
connection属性设置返回一个 Azure 密钥保管库 引用,指向该 连接字符串 中心维护的位置。 更多信息请参见定义 密钥保管库 连接。 -
App Configuration 引用:
connection属性设置返回一个 Azure 应用程序配置 引用,返回一个 连接字符串 或 密钥保管库 引用。 更多信息请参见连接文章中的 Azure 应用程序配置。 -
Connection string:
connection属性设置返回命名空间的实际连接字符串。 连接字符串必须用于事件中心命名空间,而不是事件中心本身。 由于连接字符串包含共享的秘密密钥,你应尽量考虑使用管理身份连接。 更多信息请参见定义连接。
欲了解更多关于绑定连接的信息,请参见 Azure Functions 中的 Manage connection 。
要了解如何获取 Event Hubs 命名空间的 连接字符串,请参见获取 Event Hubs 连接字符串。
异常和返回代码
| 绑定 | 参考 |
|---|---|
| 事件中心 | 操作指南 |