Azure Functions 方案

我们通常会构建系统来应对一系列的关键事件。 无论是生成 Web API、响应数据库更改,还是处理事件流或消息,都可以使用 Azure Functions 予以实现。

在许多情况下,函数与一系列云服务相集成,可提供功能丰富的实现。 以下是 Azure Functions 的一组常见(但并非详尽)的方案。

在文章顶部选择开发语言。

处理文件上传

可通过多种方式使用函数将文件引入或移出 blob 存储容器。 若要详细了解在 blob 容器上触发的选项,请参阅最佳做法文档中的使用 blob

例如,在零售解决方案中,合作伙伴系统可以将产品目录信息作为文件提交到 blob 存储中。 上传文件时,可以使用 blob 触发的函数来验证、转换文件以及将其处理到主系统中。

Diagram of a file upload process using Azure Functions.

以下教程使用事件网格触发器处理 blob 容器中的文件:

例如,将 blob 触发器与 blob 容器上的事件订阅配合使用:

[FunctionName("ProcessCatalogData")]
public static async Task Run([BlobTrigger("catalog-uploads/{name}", Source = BlobTriggerSource.EventGrid, Connection = "<NAMED_STORAGE_CONNECTION>")]Stream myCatalogData, string name, ILogger log)
{
    log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myCatalogData.Length} Bytes");

    using (var reader = new StreamReader(myCatalogData))
    {
        var catalogEntry = await reader.ReadLineAsync();
        while(catalogEntry !=null)
        {
            // Process the catalog entry
            // ...

            catalogEntry = await reader.ReadLineAsync();
        }
    }
}

实时流和事件处理

大量遥测数据是从云应用程序、IoT 设备和网络设备生成和收集的。 Azure Functions 可准实时地将这些数据作为热路径进行处理,然后将其存储在 Azure Cosmos DB 中,以供在分析仪表板中使用。

函数还可以使用事件网格等低延迟事件触发器以及 SignalR 等实时输出来准实时地处理数据。

Diagram of a real-time stream process using Azure Functions.

例如,使用事件中心触发器从事件中心读取数据,并使用输出绑定在对事件进行解批和转换后将其写入另一个事件中心:

[FunctionName("ProcessorFunction")]
public static async Task Run(
    [EventHubTrigger(
        "%Input_EH_Name%",
        Connection = "InputEventHubConnectionString",
        ConsumerGroup = "%Input_EH_ConsumerGroup%")] EventData[] inputMessages,
    [EventHub(
        "%Output_EH_Name%",
        Connection = "OutputEventHubConnectionString")] IAsyncCollector<SensorDataRecord> outputMessages,
    PartitionContext partitionContext,
    ILogger log)
{
    var debatcher = new Debatcher(log);
    var debatchedMessages = await debatcher.Debatch(inputMessages, partitionContext.PartitionId);

    var xformer = new Transformer(log);
    await xformer.Transform(debatchedMessages, partitionContext.PartitionId, outputMessages);
}

机器学习和 AI

除了数据处理之外,Azure Functions 还可用于模型推断。

例如,调用 TensorFlow 模型或将其提交到 Azure AI 服务的函数可以处理图像流并对其进行分类。

函数还可以连接到其他服务,从而帮助处理数据和执行其他 AI 相关任务,例如文本摘要

Diagram of a machine learning and AI process using Azure Functions.

运行计划任务

借助 Functions,可以基于你定义的 cron 计划运行代码。

查看如何在 Azure 门户中创建按计划运行的函数

例如,系统可能会每 15 分钟分析一次金融服务客户数据库是否包含重复条目,从而避免向同一客户进行多次通信。

Diagram of a scheduled task where a function cleans a database every 15 minutes deduplicating entries based on business logic.

[FunctionName("TimerTriggerCSharp")]
public static void Run([TimerTrigger("0 */15 * * * *")]TimerInfo myTimer, ILogger log)
{
    if (myTimer.IsPastDue)
    {
        log.LogInformation("Timer is running late!");
    }
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

    // Perform the database deduplication
}

生成可缩放的 Web API

HTTP 触发的函数可定义 HTTP 终结点。 这些终结点运行可以直接连接或通过使用绑定扩展连接到其他服务的函数代码。 可以将这些终结点组合到一个基于 Web 的 API 中。

还可以将 HTTP 触发的函数终结点用作 Webhook 集成,例如 GitHub Webhook。 通过这种方式,可以创建处理 GitHub 事件数据的函数。 若要了解详细信息,请参阅通过 Azure Functions 使用 Webhook 监视 GitHub 事件

Diagram of processing an HTTP request using Azure Functions.

有关示例,请参阅以下内容:

[FunctionName("InsertName")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req,
    [CosmosDB(
        databaseName: "my-database",
        collectionName: "my-container",
        ConnectionStringSetting = "CosmosDbConnectionString")]IAsyncCollector<dynamic> documentsOut,
    ILogger log)
{
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    string name = data?.name;

    if (name == null)
    {
        return new BadRequestObjectResult("Please pass a name in the request body json");
    }

    // Add a JSON document to the output container.
    await documentsOut.AddAsync(new
    {
        // create a random ID
        id = System.Guid.NewGuid().ToString(), 
        name = name
    });

    return new OkResult();
}

构建无服务器工作流

Functions 通常是无服务器工作流拓扑(例如逻辑应用工作流)中的计算组件。 还可以使用 Durable Functions 扩展创建长时间运行的业务流程。 有关详细信息,请参阅 Durable Functions 概述

A combination diagram of a series of specific serverless workflows using Azure Functions.

响应数据库更改

存储的数据发生更改时,可能需要在某些进程中记录、审核或执行一些其他操作。 函数触发器提供了一种很好的方式来获取数据更改通知以启动此类操作。

Diagram of a function being used to respond to database changes.

请开考虑以下示例:

创建可靠消息系统

可以将 Functions 与 Azure 消息服务配合使用来创建高级事件驱动的消息解决方案。

例如,可以在 Azure 存储队列上使用触发器将一系列函数执行链接在一起。 或者对联机排序系统使用服务总线队列和触发器。

Diagram of Azure Functions in a reliable message system.

以下文章介绍如何将输出写入存储队列。

以下文章介绍如何从 Azure 服务总线队列或主题进行触发。

后续步骤