Azure Functions 触发器和绑定
编写由 HTTP 触发的函数,添加输出绑定以写入 Azure 队列存储,并了解消耗计划的自动缩放模型。
Azure Functions 触发器和绑定 是 CoddyKit 上的免费 Azure Fundamentals 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Azure Fundamentals 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Azure Fundamentals 课程共包含 4 节课。
什么是 Azure Functions?
Azure Functions 是一项无服务器计算服务,可以让您在无需管理任何基础设施的情况下,响应事件运行小型代码单元(函数)。您只需为函数运行期间使用的执行时间和内存付费;函数处于空闲状态时不产生费用。Functions 非常适合事件驱动任务、轻量级 API、计划任务,以及在没有持久服务器的情况下集成云服务。
触发器:是什么启动了函数
每个 Azure Function 必须且只能有一个触发器,用于定义导致函数执行的事件。常见触发器包括 HTTP(传入的 HTTP 请求)、Timer(CRON 计划)、Blob Storage(容器中的新 Blob)、Queue Storage(队列中的新消息)、Event Hub(事件流)、Service Bus(队列或主题消息)和 Cosmos DB(更改源)。触发器接收事件数据,并将其传递给您的函数代码。
// HTTP trigger function (JavaScript/Node.js)
module.exports = async function (context, req) {
const name = req.query.name || (req.body && req.body.name);
const message = name ? 'Hello, ' + name : 'Pass a name in the query or body';
context.res = {
status: 200,
body: { message }
};
};Function.json:触发器和绑定配置
在非编译语言(JavaScript、Python)中,每个函数目录内的 function.json 文件都会声明其触发器和绑定。此文件将事件源和输出映射到函数代码中的命名参数。对于 C# 和 Java,绑定通过代码中的属性或注释直接声明。Functions 运行时会读取配置,并自动设置与 Azure 服务的连接。
// function.json — HTTP trigger + Queue output binding
{
'bindings': [
{
'authLevel': 'function',
'type': 'httpTrigger',
'direction': 'in',
'name': 'req',
'methods': ['post']
},
{
'type': 'http',
'direction': 'out',
'name': 'res'
},
{
'type': 'queue',
'direction': 'out',
'name': 'outputQueue',
'queueName': 'processing-queue',
'connection': 'AzureWebJobsStorage'
}
]
}输出绑定:写入服务
输出绑定可以让函数向 Azure 服务(Blob Storage、Queue Storage、Cosmos DB、Event Hub 等)写入数据,而无需管理 SDK 或连接字符串。您只需为输出绑定参数赋值,Functions 运行时会处理写入操作。这会大幅减少样板代码,并使函数与特定 Azure 服务的实现细节解耦。
// HTTP trigger with Queue output binding (Node.js)
module.exports = async function (context, req) {
const orderData = req.body;
// Write to queue via output binding -- no SDK needed!
context.bindings.outputQueue = JSON.stringify({
orderId: orderData.id,
timestamp: new Date().toISOString()
});
context.res = { status: 202, body: 'Order queued' };
};使用 CRON 表达式的 Timer 触发器
Timer 触发器会按照CRON 表达式定义的计划运行函数。Azure Functions 使用包含 6 个部分的 CRON:{seconds} {minutes} {hours} {day} {month} {day-of-week}。使用 0 0 * * * * 表示每小时运行,使用 0 0 0 * * * 表示每天午夜运行,使用 0 0 9-17 * * 1-5 表示工作日工作时间内每小时运行一次。Timer 函数适用于清理任务、报告生成和运行状况检查。
// Timer trigger — runs every day at 02:00 UTC
// function.json binding:
// {
// 'type': 'timerTrigger',
// 'schedule': '0 0 2 * * *',
// 'name': 'myTimer'
// }
module.exports = async function (context, myTimer) {
const now = new Date().toISOString();
context.log('Daily cleanup started at', now);
// ... perform cleanup logic ...
context.log('Cleanup completed');
};Consumption 计划:无服务器扩展
在 Consumption 计划中,Azure Functions 会根据触发事件速率自动从零扩展到数百个实例。您只需为执行次数和消耗的 GB-秒内存付费;每月前 100 万次执行免费。Functions 主机可以将 HTTP 触发器扩展到最多 200 个实例,并根据队列消息数量并发扩展队列触发器。冷启动(空闲后首次执行)会增加短暂延迟,使用 Premium 计划的预热实例可以缓解这一问题。
# View billing details for a function app
az functionapp show \
--name myFunctionApp \
--resource-group MyRG \
--query '{name:name, plan:serverFarmId, state:state}'
# Create a Function App on Consumption plan
az functionapp create \
--name myFunctionApp \
--resource-group MyRG \
--consumption-plan-location eastus \
--runtime node \
--runtime-version 18 \
--storage-account mystorageaccountPremium 和专用计划
Premium 计划通过保留预热实例来消除冷启动,支持 VNet 集成,并允许更长的执行超时时间(最多 60 分钟)。专用(App Service)计划会让函数与 Web 应用在同一个 App Service 计划上运行,适合需要可预测成本或已有可用 App Service 计算资源的情况。如果您需要真正的无服务器经济模式,请选择 Consumption;如果函数对性能敏感或需要连接 VNet,请选择 Premium。
# Create a Function App on Premium plan (EP1)
az functionapp plan create \
--name MyPremiumPlan \
--resource-group MyRG \
--location eastus \
--sku EP1 \
--is-linux
az functionapp create \
--name myFunctionAppPremium \
--resource-group MyRG \
--plan MyPremiumPlan \
--runtime python \
--runtime-version 3.11 \
--storage-account mystorageaccount部署 Azure Functions
您可以使用 Azure Functions Core Tools(func azure functionapp publish)、VS Code 扩展、通过 Azure CLI 执行的 ZIP 部署,或者在 Azure Pipelines 或 GitHub Actions 中使用 CI/CD 管道来部署 Azure Functions。在生产环境中,请始终通过管道而非开发人员计算机进行部署,以确保经过测试并带有标签的版本进入生产环境。Functions 运行时还支持Docker 容器部署,从而完全控制运行时环境。
# Local development: install Core Tools
npm install -g azure-functions-core-tools@4
# Start locally (triggers work against real Azure services)
func start
# Deploy to Azure
func azure functionapp publish myFunctionApp
# Or deploy via Azure CLI (ZIP deploy)
zip -r function.zip . --exclude '.git/*'
az functionapp deployment source config-zip \
--name myFunctionApp \
--resource-group MyRG \
--src function.zip应用程序设置和 Key Vault 引用
Function Apps 会将配置存储在应用程序设置中,这些设置会在函数代码中显示为环境变量。请将连接字符串、API 密钥和机密存储为应用程序设置。在生产环境中,请使用 Key Vault 引用,这样值会存储在 Key Vault 中,应用程序设置中只按名称引用该值,从而避免机密出现在门户和部署构件中。请在函数应用上启用托管标识,以便在无需凭据的情况下向 Key Vault 进行身份验证。
# Set application settings
az functionapp config appsettings set \
--name myFunctionApp \
--resource-group MyRG \
--settings \
STORAGE_CONNECTION='@Microsoft.KeyVault(SecretUri=https://mykv.vault.azure.net/secrets/storage-conn/)' \
COSMOS_DB_URI='https://mycosmosdb.documents.azure.com'
# In function code, read as normal env var
# const storageConn = process.env['STORAGE_CONNECTION'];使用 Application Insights 监视 Functions
当您提供检测密钥或连接字符串时,Azure Functions 会自动与 Application Insights 集成。每次函数执行都会作为请求进行跟踪,包括持续时间、成功或失败状态以及自定义属性。在测试期间,请使用 Application Insights 的实时指标实时观察执行情况,并使用故障窗格通过完整的异常跟踪和依赖项调用来诊断错误。
# Connect Application Insights to a Function App
az functionapp config appsettings set \
--name myFunctionApp \
--resource-group MyRG \
--settings \
APPLICATIONINSIGHTS_CONNECTION_STRING='InstrumentationKey=xxxxxxxx;...'
# Custom telemetry in function code (Node.js)
const appInsights = require('applicationinsights');
appInsights.setup().start();
const client = appInsights.defaultClient;
client.trackEvent({ name: 'OrderProcessed', properties: { orderId: '123' } });并发和扩展行为
对于队列触发的函数,Functions 主机会并行处理多条消息。在 host.json 中配置 batchSize,以控制单个实例同时处理的消息数量。对于 HTTP 触发器,扩展会自动添加新实例。使用 maxConcurrentCalls(Service Bus 触发器)或 maxPollingInterval(队列触发器)调整吞吐量,避免在扩展事件期间使数据库等下游服务不堪重负。
// host.json — tune queue trigger concurrency
{
'version': '2.0',
'extensions': {
'queues': {
'batchSize': 16, // messages per instance
'newBatchThreshold': 8, // fetch more when < 8 remain
'maxPollingInterval': '00:00:02',
'visibilityTimeout': '00:05:00'
}
},
'functionTimeout': '00:10:00'
}快速检查
测试您对本课中 Microsoft Azure 基础知识(AZ-900)概念的理解。
课程回顾
本课中您学习了:触发器定义启动函数的事件(HTTP、Timer、Queue、Blob 等);输出绑定让函数无需编写 SDK 代码即可向 Azure 服务写入数据;Consumption 计划提供真正的无服务器按执行付费扩缩容能力,并且可以从零开始。接下来我们将探索用于有状态工作流的 Durable Functions。
常见问题解答
「Azure Functions 触发器和绑定」课时是免费的吗?
是的 — 「Azure Functions 触发器和绑定」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Azure Fundamentals 课程的其余内容,请升级到 CoddyKit PRO。 Azure Fundamentals 课程共包含 4 节课。
「Azure Functions 触发器和绑定」这节课中我会学到什么?
编写由 HTTP 触发的函数,添加输出绑定以写入 Azure 队列存储,并了解消耗计划的自动缩放模型。 你通过在浏览器中直接运行的动手代码来练习 Azure Fundamentals,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Azure Fundamentals 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Azure Fundamentals 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「Azure Functions 触发器和绑定」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Azure Fundamentals 课中编写并运行代码吗?
能。每节 Azure Fundamentals 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Azure Functions 触发器和绑定
- 使用 Durable Functions 编排有状态工作流
- Azure Logic Apps
- 事件网格和事件驱动架构