Azure Learn AZ-204 The Hard Way | 實作 AZ-204 Lab 02 Azure Functions


  1. Lab02 - Azure Functions
    1. Pre Setting
    2. Create Function App
    3. Function Coding
    4. Http Request Trigger Function
      1. HttpRepl
    5. Function triggers on a schedule
    6. Function With Services
    7. Deploy Function to Azure
  2. App Functions 相關知識
  3. 實戰 Azure Functions 心得

實作 AZ-204 證照測驗準備的實驗課程,從實驗課程中精熟 AZ-204 的測驗重點以及工具操作。本次要實驗的是如何使用 ServerLess 架構下的主角 Azure Functions。

logo

Lab02 - Azure Functions

詳細的實驗流程可以參考微軟在 GitHub上的專案

圖片來源:微軟

Pre Setting

首先建立 Storage Account

取得 API Key 以及 ConnectionString 提供後續 Web App 使用

建立 Storage Container

上述圖片沿用 Lab01 的部分。

Create Function App

建立 Function App 選擇對應的 Runtime:

接著在 Hosting 的地方,連結對應的 Storage Account 並且將 Plan 設定為 Consumption

需要安裝 Azure Functions Core Toolss

Function Coding

藉由安裝 Azure Functions Core Tools 而可以使用 func CLI 來建立專案,此外也可以使用 Visual Studio 建立 Azure Functions 的專案。

func init --worker-runtime dotnet --force

AzureWebJobsStorage 取代為 Storage Account 的 Connection String。

local.settings.json

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=*;AccountKey=*;EndpointSuffix=core.windows.net",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet"
    }
}

編譯專案

dotnet build

Http Request Trigger Function

使用 func CLI 使用 template 的方式建立程式碼樣板用以編輯

func new --template "HTTP trigger" --name "Echo"

將預設的內容移除,並輸入下列程式

using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

public static class Echo
{
    [FunctionName("Echo")]
    public static IActionResult Run(
        [HttpTrigger("POST")] HttpRequest request,
        ILogger logger)
    {
        logger.LogInformation("Received a request");
        return new OkObjectResult(request.Body);
    }
}

編譯專案以進行測試

func start --build

原本實驗內容只是原封不動將 Request 的 Body 顯示出來,我們額外加上一點處理,讓回傳的內容都變為 UpperCase:

處理上要注意因為 request.body 是 Stream 物件,所以必須要用 StreamReader 來取值,再加上 C# 的 String Method ToUpper 就可以順利將內容轉換為 UpperCase 囉 🙂

using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Threading.Tasks;

public static class Echo
{
    [FunctionName("Echo")]
    public static async Task<IActionResult> RunAsync(
        [HttpTrigger("POST")] HttpRequest request,
        ILogger logger)
    {
        logger.LogInformation("Received a request");

    string requestContent;

    using (var reader = new StreamReader(request.Body))
    {
        requestContent = await reader.ReadToEndAsync();
        request.Body.Seek(0, SeekOrigin.Begin);
    }

        return new OkObjectResult(requestContent.ToUpper());
    }
}

編譯專案測試 Everything will be alright

func start --build

HttpRepl

另外開啟新的 Terminal 執行下列 script 進行安裝 httprepl 用以測試 localhost 所執行的 Func。

dotnet tool install -g Microsoft.dotnet-httprepl

執行下列 command 使用 httprepl 進行測試

httprepl http://localhost:7071
cd api
cd getsettinginfo
get
exit

除了使用 HttpRepl 外,也可以使用 PostMan 來進行 HTTP 的測試或者是使用 PowerShell 來進行測試。

Function triggers on a schedule

建立一個定時執行的 Function

func new --template "Timer trigger" --name "Recurring"

Recurring.cs

將原本的程式碼刪除,並輸入下列的內容:

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

namespace func
{
    public static class Recurring
    {
        [FunctionName("Recurring")]
        public static void Run([TimerTrigger("*/30 * * * * *")]TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
        }
    }
}

編譯並執行專案,可以觀察到每 30 秒會觸發一次 Function

func start --build

Function With Services

在 Storage 的 Container 中把 settings.json 上傳。

使用 func CLI 建立新的程式碼

func new --template "HTTP trigger" --name "GetSettingInfo"

GetSettingInfo.cs

將原本的程式碼刪除,並以下列內容取代:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;

public static class GetSettingInfo
{
    [FunctionName("GetSettingInfo")]
    public static IActionResult Run(
        [HttpTrigger("GET")] HttpRequest request,
        [Blob("content/settings.json")] string json)
        => new OkObjectResult(json);
}

安裝 Extensions Microsoft.Azure.WebJobs.Extensions.Storage 以與其他 Service 互動

func extensions install 
  --package Microsoft.Azure.WebJobs.Extensions.Storage 
  --version 4.0.4

編譯專案

func start --build

另外開啟新的 Terminal 執行下列 command 使用 httprepl 進行測試

httprepl http://localhost:7071
cd api
cd getsettinginfo
get
exit

可以看到回應的結果

Deploy Function to Azure

az login
func azure functionapp publish <function-app-name>

上傳成功後可以在 Azure Portal 看到剛剛使用的 Echo, Recurring 以及 GetSettingInfo 三個 function。

在 Azure Portal 上也有提供介面可以直接對 Function 進行測試:

App Functions 相關知識

Duralble Function

Task Hubs

實戰 Azure Functions 心得

Azure Functions 是雲端應用的虛擬化極致,將資訊服務的功能所需的程式碼設計以函式的方式實現,要提供服務的 Web 或者其他 Client 端只要透過呼叫 Azure Functions 的方式,讓 Functions 去完成後端邏輯,就可以實現整個服務流程。

每一個 Function 扮演獨立的功能單元,讓設計可以達到分離關注點,但帶來的挑戰就是原本習慣的 MVC 開發模式,該如何區分成前後端的開發方式,並且更進階的將後端設計為 ServerLess 就是挑戰所在 😎

但學習 Function 對於日常玩具級的應用多了一項開發解決方案的選擇 🤗