다음을 통해 공유


Azure Functions에 대한 Dapr 서비스 호출 트리거

다음 Dapr 이벤트를 사용하여 Dapr 서비스 호출에서 Azure Functions를 트리거할 수 있습니다.

Dapr 확장의 설정 및 구성 세부 정보에 대한 자세한 내용은 Dapr 확장 개요를 참조하세요.

Example

C# 함수는 다음 C# 모드 중 하나를 사용하여 만들 수 있습니다.

Execution model Description
격리된 작업자 모델 함수 코드는 별도의 .NET 작업자 프로세스에서 실행됩니다. 지원되는 .NET 및 .NET Framework 버전과 함께 사용합니다. 자세한 내용은 격리된 작업자 모델에서 C# Azure Functions를 실행하기 위한 가이드를 참조하세요.
In-process model 함수 코드는 Functions 호스트 프로세스와 동일한 프로세스에서 실행됩니다. .NET의 LTS(장기 지원) 버전만 지원합니다. 자세한 내용은 Azure Functions를 사용하여 C# 클래스 라이브러리 함수 개발을 참조하세요.
[FunctionName("CreateNewOrder")]
public static void Run(
    [DaprServiceInvocationTrigger] JObject payload,
    [DaprState("%StateStoreName%", Key = "order")] out JToken order,
    ILogger log)
{
    log.LogInformation("C# function processed a CreateNewOrder request from the Dapr Runtime.");

    // payload must be of the format { "data": { "value": "some value" } }
    order = payload["data"];
}

Dapr 서비스 호출 트리거에 대한 Java 코드는 다음과 같습니다.

@FunctionName("CreateNewOrder")
public String run(
        @DaprServiceInvocationTrigger(
            methodName = "CreateNewOrder") 
)

개체를 사용하여 다음을 app 등록합니다 daprInvokeOutput.

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 };
    }
});

The following examples show Dapr triggers in a function.json file and PowerShell code that uses those bindings.

Here's the function.json file for daprServiceInvocationTrigger:

{
  "bindings": [
    {
      "type": "daprServiceInvocationTrigger",
      "name": "payload",
      "direction": "in"
    }
  ]
}

For more information about function.json file properties, see the Configuration section.

In code:

using namespace System
using namespace Microsoft.Azure.WebJobs
using namespace Microsoft.Extensions.Logging
using namespace Microsoft.Azure.WebJobs.Extensions.Dapr
using namespace Newtonsoft.Json.Linq

param (
    $payload
)

# C# function processed a CreateNewOrder request from the Dapr Runtime.
Write-Host "PowerShell function processed a CreateNewOrder request from the Dapr Runtime."

# Payload must be of the format { "data": { "value": "some value" } }

# Convert the object to a JSON-formatted string with ConvertTo-Json
$jsonString = $payload| ConvertTo-Json

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name order -Value $payload["data"]

다음 예제에서는 v2 Python 프로그래밍 모델을 사용하는 Dapr 서비스 호출 트리거를 보여 줍니다. Python 함수 앱 코드에서 사용하려면 다음을 daprServiceInvocationTrigger 수행합니다.

import logging
import json
import azure.functions as func

app = func.FunctionApp()

@app.function_name(name="RetrieveOrder")
@app.dapr_service_invocation_trigger(arg_name="payload", method_name="RetrieveOrder")
@app.dapr_state_input(arg_name="data", state_store="statestore", key="order")
def main(payload, data: str) :
    # Function should be invoked with this command: dapr invoke --app-id functionapp --method RetrieveOrder  --data '{}'
    logging.info('Python function processed a RetrieveOrder request from the Dapr Runtime.')
    logging.info(data)

Attributes

In the in-process model, use the DaprServiceInvocationTrigger to trigger a Dapr service invocation binding, which supports the following properties.

Parameter Description
MethodName Optional. Dapr 호출자가 사용해야 하는 메서드의 이름입니다. 지정하지 않으면 함수 이름이 메서드 이름으로 사용됩니다.

Annotations

주석 DaprServiceInvocationTrigger 을 사용하면 Dapr 런타임에서 호출되는 함수를 만들 수 있습니다.

Element Description
methodName 메서드 이름입니다.

Configuration

다음 표에서는 코드에 설정한 바인딩 구성 속성을 설명합니다.

Property Description
type daprServiceInvocationTrigger로 설정해야 합니다.
name 함수 코드에서 Dapr 데이터를 나타내는 변수의 이름입니다.

다음 표에서는 function.json 파일에 설정된 바인딩 구성 속성을 설명합니다.

function.json property Description
type daprServiceInvocationTrigger로 설정해야 합니다.
name 함수 코드에서 Dapr 데이터를 나타내는 변수의 이름입니다.

다음 표에서는 Python 코드에 설정한 @dapp.dapr_service_invocation_trigger의 바인딩 구성 속성을 설명합니다.

Property Description
method_name Dapr 데이터를 나타내는 변수의 이름입니다.

See the Example section for complete examples.

Usage

Dapr 서비스 호출 트리거를 사용하려면 서비스 호출 트리거와 함께 사용할 구성 요소 및 공식 Dapr 설명서에서 설정하는 방법에 대해 자세히 알아봅니다.

Python v2에서 daprServiceInvocationTrigger를 사용하려면 올바른 종속성으로 프로젝트를 설정합니다.

  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
    

Next steps

Dapr 서비스 호출에 대해 자세히 알아봅니다.