
关于
Azure Functions 开发专家模式,包括隔离进程模型、触发器绑定和最佳实践
name: azure-functions description: Azure Functions 开发专家模式,包括隔离进程模型、Durable Functions 编排、冷启动优化和生产模式。涵盖 .NET、Python 和 Node.js 编程模型。 risk: none source: vibeship-spawner-skills (Apache 2.0) date_added: 2026-02-27
Azure Functions
Azure Functions 开发专家模式,包括隔离进程模型、Durable Functions 编排、冷启动优化和生产模式。涵盖 .NET、Python 和 Node.js 编程模型。
模式
隔离进程模型 (.NET)
具有进程隔离的现代 .NET 执行模型
适用场景:构建新的 .NET Azure Functions 应用
模板
// Program.cs - Isolated Worker Model
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(services =>
{
// Add Application Insights
services.AddApplicationInsightsTelemetryWorkerService();
services.ConfigureFunctionsApplicationInsights();
// Add HttpClientFactory (prevents socket exhaustion)
services.AddHttpClient();
// Add your services
services.AddSingleton<IMyService, MyService>();
})
.Build();
host.Run();
// HttpTriggerFunction.cs
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
public class HttpTriggerFunction
{
private readonly ILogger<HttpTriggerFunction> _logger;
private readonly IMyService _service;
public HttpTriggerFunction(
ILogger<HttpTriggerFunction> logger,
IMyService service)
{
_logger = logger;
_service = service;
}
[Function("HttpTrigger")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
{
_logger.LogInformation("Processing request");
try
{
var result = await _service.ProcessAsync(req);
var response = req.CreateResponse(HttpStatusCode.OK);
await response.WriteAsJsonAsync(result);
return response;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing request");
var response = req.CreateResponse(HttpStatusCode.InternalServerError);
await response.WriteAsJsonAsync(new { error = "Internal server error" });
return response;
}
}
}
注意事项
- In-process 模型将于 2026 年 11 月弃用
- 隔离进程支持 .NET 8、9、10 和 .NET Framework
- 完整的依赖注入支持
- 自定义中间件支持
Node.js v4 编程模型
面向 TypeScript/JavaScript 的现代代码优先方式
适用场景:构建 Node.js Azure Functions
模板
// src/functions/httpTrigger.ts
import { app, HttpRequest, HttpResponseInit, InvocationContext } from "@azure/functions";
export async function httpTrigger(
request: HttpRequest,
context: InvocationContext
): Promise<HttpResponseInit> {
context.log(`Http function processed request for url "${request.url}"`);
try {
const name = request.query.get("name") || (await request.text()) || "world";
return {
status: 200,
jsonBody: { message: `Hello, ${name}!` }
};
} catch (error) {
context.error("Error processing request:", error);
return {
status: 500,
jsonBody: { error: "Internal server error" }
};
}
}
// Register function with app object
app.http("httpTrigger", {
methods: ["GET", "POST"],
authLevel: "function",
handler: httpTrigger
});
// Timer trigger example
app.timer("timerTrigger", {
schedule: "0 */5 * * * *", // Every 5 minutes
handler: async (myTimer, context) => {
context.log("Timer function executed at:", new Date().toISOString());
}
});
// Blob trigger example
app.storageBlob("blobTrigger", {
path: "samples-workitems/{name}",
connection: "AzureWebJobsStorage",
handler: async (blob, context) => {
context.log(`Blob trigger processing: ${context.triggerMetadata.name}`);
context.log(`Blob size: ${blob.length} bytes`);
}
});
注意事项
- v4 模型以代码为中心,无需 function.json 文件
- 使用类似 Express.js 的 app 对象
- TypeScript 一等公民支持
- 所有触发器在代码中注册
Python v2 编程模型
基于装饰器的 Python 函数方式
适用场景:构建 Python Azure Functions
模板
# function_app.py
import azure.functions as func
import logging
import json
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
@app.route(route="hello", methods=["GET", "POST"])
async def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
logging.info("Python HTTP trigger function processed a request.")
try:
name = req.params.get("name")
if not name:
req_body = req.get_json()
name = req_body.get("name")
except ValueError:
name = None
if name:
return func.HttpResponse(f"Hello, {name}!")
else:
return func.HttpResponse(
"Please pass a name on the query string or in the request body",
status_code=400
)
注意事项
- v2 模型使用装饰器,无需 function.json
- 支持异步函数
- 蓝图模式用于大型应用
- 内置 HTTP、Timer、Blob、Queue 触发器支持
兼容工具
Claude CodeCursor
标签
后端开发
