共用方式為


Azure Functions 的 Dapr 叫用輸出繫結

Dapr 叫用輸出繫結可讓您在函式執行期間叫用另一個 Dapr 應用程式。

如需 Dapr 延伸模組的安裝和設定詳細資料,請參閱 Dapr 延伸模組概觀

範例

您可以使用下列其中一種 C# 模式來建立 C# 函式:

執行模型 描述
隔離式背景工作模型 您的函數程式碼在個別的 .NET 背景工作處理序中執行。 搭配支援的 .NET 和 .NET Framework 版本使用。 若要深入了解,請參閱開發 .NET 隔離式背景工作處理序函數
同處理序模型 您的函數程式碼執行的處理序與 Functions 主機處理序相同。 僅支援長期支援 (LTS) 的 .NET 版本。 若要深入了解,請參閱開發 .NET 類別庫函數

下列範例示範如何使用 Dapr 叫用輸出繫結來執行裝載於另一個 Dapr 化應用程式中的 Dapr 服務叫用作業。 在此範例中,函式的作用類似於 Proxy。

[FunctionName("InvokeOutputBinding")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = "invoke/{appId}/{methodName}")] HttpRequest req,
    [DaprInvoke(AppId = "{appId}", MethodName = "{methodName}", HttpVerb = "post")] IAsyncCollector<InvokeMethodParameters> output,
    ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

    var outputContent = new InvokeMethodParameters
    {
        Body = requestBody
    };

    await output.AddAsync(outputContent);

    return new OkResult();
}

下列範例會使用 DaprInvokeOutput 繫結搭配 HttpTrigger 來建立 "InvokeOutputBinding" 函式:

@FunctionName("InvokeOutputBinding")
public String run(
        @HttpTrigger(
            name = "req",
            methods = {HttpMethod.GET, HttpMethod.POST},
            authLevel = AuthorizationLevel.ANONYMOUS,
            route = "invoke/{appId}/{methodName}")
            HttpRequestMessage<Optional<String>> request,
        @DaprInvokeOutput(
            appId = "{appId}", 
            methodName = "{methodName}", 
            httpVerb = "post")
        OutputBinding<String> payload,
        final ExecutionContext context)

在下列範例中,Dapr 叫用輸出繫結會與 HTTP 觸發程序配對,該程式是由 app 物件所註冊:

const { app, trigger } = require('@azure/functions');

app.generic('InvokeOutputBinding', {
    trigger: trigger.generic({
        type: 'httpTrigger',
        authLevel: 'anonymous',
        methods: ['POST'],
        route: "invoke/{appId}/{methodName}",
        name: "req"
    }),
    return: daprInvokeOutput,
    handler: async (request, context) => {
        context.log("Node HTTP trigger function processed a request.");

        const payload = await request.text();
        context.log(JSON.stringify(payload));

        return { body: payload };
    }
});

下列範例顯示 function.json 檔案中的 Dapr 觸發程序,以及使用這些繫結的 PowerShell 程式碼。

以下是 daprInvokefunction.json 檔案:

{
  "bindings":
    {
      "type": "daprInvoke",
      "direction": "out",
      "appId": "{appId}",
      "methodName": "{methodName}",
      "httpVerb": "post",
      "name": "payload"
    }
}

如需 function.json 檔案屬性的詳細資訊,請參閱設定一節。

程式碼:

using namespace System.Net

# Input bindings are passed in via param block.
param($req, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Host "Powershell InvokeOutputBinding processed a request."

$req_body = $req.Body

$invoke_output_binding_req_body = @{
    "body" = $req_body
}

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name payload -Value $invoke_output_binding_req_body

Push-OutputBinding -Name res -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::OK
    Body = $req_body
})

下列範例示範使用 v2 Python 程式設計模型的 Dapr 叫用輸出繫結。 若要在您的 Python 函式應用程式程式碼中使用 daprInvoke

import logging
import json
import azure.functions as func

app = func.FunctionApp()

@app.function_name(name="InvokeOutputBinding")
@app.route(route="invoke/{appId}/{methodName}", auth_level=dapp.auth_level.ANONYMOUS)
@app.dapr_invoke_output(arg_name = "payload", app_id = "{appId}", method_name = "{methodName}", http_verb = "post")
def main(req: func.HttpRequest, payload: func.Out[str] ) -> str:
    # request body must be passed this way "{\"body\":{\"value\":{\"key\":\"some value\"}}}" to use the InvokeOutputBinding, all the data must be enclosed in body property.
    logging.info('Python function processed a InvokeOutputBinding request from the Dapr Runtime.')

    body = req.get_body()
    logging.info(body)
    if body is not None:
        payload.set(body)
    else:
        logging.info('req body is none')
    return 'ok'

屬性

同處理模型中,使用 DaprInvoke 屬性來定義 Dapr 叫用輸出繫結,其支援下列參數:

參數 描述 可透過屬性傳送 可透過 RequestBody 傳送
AppId 要叫用的 Dapr 應用程式識別碼。 ✔️ ✔️
MethodName 要叫用的應用程式方法名稱。 ✔️ ✔️
HttpVerb 選擇性。 使用應用程式叫用的 Http 指令動詞。 預設值為 POST ✔️ ✔️
本文 必要。 要求的主體。 ✔️

註釋

DaprInvokeOutput 註釋允許您讓函式叫用並接聽輸出繫結。

元素 描述 可透過屬性傳送 可透過 RequestBody 傳送
應用程式識別碼 叫用繫結中涉及之應用程式的應用程式識別碼。 ✔️ ✔️
methodName 方法變數的名稱。 ✔️ ✔️
httpVerb 張貼或取得。 ✔️ ✔️
body 必要。 要求的主體。 ✔️

組態

下表說明您在程式碼中設定的繫結設定屬性。

屬性 說明 可透過屬性傳送 可透過 RequestBody 傳送
應用程式識別碼 叫用繫結中涉及之應用程式的應用程式識別碼。 ✔️ ✔️
方法 張貼或取得。 ✔️ ✔️
body 必要。 要求的主體。 ✔️

下表說明您在 function.json 檔案中設定的繫結設定屬性。

function.json 屬性 描述 可透過屬性傳送 可透過 RequestBody 傳送
應用程式識別碼 叫用繫結中涉及之應用程式的應用程式識別碼。 ✔️ ✔️
methodName 方法變數的名稱。 ✔️ ✔️
httpVerb 張貼或取得。 ✔️ ✔️
body 必要。 要求的主體。 ✔️

下表說明您在 Python 程式碼中設定的 @dapp.dapr_invoke_output 繫結組態屬性。

屬性 說明 可透過屬性傳送 可透過 RequestBody 傳送
app_id 叫用繫結中涉及之應用程式的應用程式識別碼。 ✔️ ✔️
method_name 方法變數的名稱。 ✔️ ✔️
http_verb 設為 postget ✔️ ✔️
body 必要。 要求的主體。 ✔️

如果屬性在 Attributes 和 RequestBody 中都有定義,則系統會優先考量 RequestBody 中提供的資料。

如需完整範例,請參閱範例一節。

使用方式

若要使用 Dapr 服務叫用輸出繫結,請在官方 Dapr 文件中深入了解如何使用 Dapr 服務叫用

若要在 Python v2 中使用 daprInvoke,請設定您的專案使其具備正確的相依性。

  1. 建立並啟用虛擬環境

  2. requirements.text 檔案中新增以下這一行:

    azure-functions==1.18.0b3
    
  3. 在終端機中,安裝 Python 程式庫。

    pip install -r .\requirements.txt
    
  4. 使用下列組態修改您的 local.setting.json 檔案:

    "PYTHON_ISOLATE_WORKER_DEPENDENCIES":1
    

下一步

深入了解 Dapr 服務叫用。