共用方式為


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.

執行排程的工作

函式可讓您根據所定義的 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 事件之資料的函式。 若要深入了解,請參閱使用 Webhook 搭配 Azure Functions監視 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();
}

建置無伺服器工作流程

函式通常是無伺服器工作流程拓撲中的計算元件,例如 Logic Apps 工作流程。 您也可以使用 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 服務匯流排佇列或主題觸發。

下一步