云函数
azure-functions、gcp-functions。
30 分钟
云函数
Serverless Functions(FaaS) 把 运行时、伸缩、补丁 交给云平台,开发者只上传 函数代码 + 触发器配置。本课聚焦 Azure Functions 与 GCP Cloud Functions(第 2 代),衔接 dcp-azure 与 devops-cloud-essentials,补全 /roadmaps/devops 的 serverless / event-driven 分支。与长期运行的 Spring Boot(CodeRoadMap backend)形成 「核心 API 常驻 + 边缘任务函数化」 的组合架构。
学习目标
- 理解 FaaS 冷启动、并发限制、执行时长、计费模型
- 会用 HTTP 触发器、队列触发器、定时触发器 实现 CodeRoadMap 周边任务(邮件、Webhook、批处理)
- 对比 Azure Functions 与 GCP Cloud Functions 在运行时、VPC 接入、密钥集成上的差异
适用场景矩阵
| 场景 | 适合 FaaS | 更适合容器/VM |
|---|---|---|
| Webhook 接收、轻量转换 | ✅ | |
| 定时清理、报表生成 | ✅ | |
| 高 QPS 核心 REST API | 需优化 | ✅ Spring Boot / Go |
| 长连接 WebSocket | ❌ | ✅ |
| 大内存批处理 (>8GB) | 受限 | ✅ Batch / K8s Job |
CodeRoadMap 核心:App Service / K8s Deployment(backend + platform)
周边函数:
- 用户注册发送验证邮件(Queue 触发)
- GitHub Webhook 同步课程 draft(HTTP 触发)
- 每日学习统计聚合(Cron 触发)
Azure Functions 示例
// HttpTrigger — GitHub Webhook 验签后写入 Queue
const crypto = require('crypto');
module.exports = async function (context, req) {
const sig = req.headers['x-hub-signature-256'];
const secret = process.env.GITHUB_WEBHOOK_SECRET;
const hmac = crypto.createHmac('sha256', secret);
hmac.update(JSON.stringify(req.body));
const expected = 'sha256=' + hmac.digest('hex');
if (sig !== expected) {
context.res = { status: 401, body: 'Invalid signature' };
return;
}
context.bindings.outputQueueItem = JSON.stringify({
repo: req.body.repository.full_name,
commits: req.body.commits?.length ?? 0,
});
context.res = { status: 202, body: 'Accepted' };
};
// function.json / host.json 概念配置
{
"bindings": [
{
"type": "httpTrigger",
"direction": "in",
"authLevel": "function",
"methods": ["post"],
"route": "github/webhook"
},
{
"type": "queue",
"direction": "out",
"queueName": "content-sync",
"connection": "AzureWebJobsStorage"
}
]
}