Dapr 発行出力バインドを使用すると、関数の実行中に Dapr トピックにメッセージを発行できます。
Dapr 拡張機能のセットアップと構成について詳しくは、Dapr 拡張機能の概要に関する記事をご覧ください。
Example
A C# 関数は、次の C# モードのいずれかを使用して作成できます。
| Execution model | Description |
|---|---|
| 分離ワーカー モデル | 関数コードは、別の .NET ワーカー プロセスで実行されます。 .NET と .NET Framework のサポートされているバージョンで使います。 詳細については、 分離ワーカー モデルで C# Azure Functions を実行するためのガイドを参照してください。 |
| In-process model | 関数コードは、Functions ホスト プロセスと同じプロセスで実行されます。 .NET の長期サポート (LTS) バージョンのみをサポートします。 詳細については、「Azure Functions を使用する C# クラス ライブラリ関数を開発する」を参照してください。 |
次の例では、Dapr 発行出力バインドを使用して、パブリッシュ/サブ コンポーネントとトピックに対して Dapr 発行操作を実行する方法を示します。
[FunctionName("PublishOutputBinding")]
public static void Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "topic/{topicName}")] HttpRequest req,
[DaprPublish(PubSubName = "%PubSubName%", Topic = "{topicName}")] out DaprPubSubEvent pubSubEvent,
ILogger log)
{
string requestBody = new StreamReader(req.Body).ReadToEnd();
pubSubEvent = new DaprPubSubEvent(requestBody);
}
次の例では、"TransferEventBetweenTopics" バインディングとDaprPublishOutputを使用してDaprTopicTrigger関数を作成します。
@FunctionName("TransferEventBetweenTopics")
public String run(
@DaprTopicTrigger(
pubSubName = "%PubSubName%",
topic = "A")
String request,
@DaprPublishOutput(
pubSubName = "%PubSubName%",
topic = "B")
OutputBinding<String> payload,
final ExecutionContext context) throws JsonProcessingException {
context.getLogger().info("Java function processed a TransferEventBetweenTopics request from the Dapr Runtime.");
}
次の例では、Dapr 発行出力バインドは、 app オブジェクトによって登録される HTTP トリガーとペアになっています。
const { app, trigger } = require('@azure/functions');
app.generic('PublishOutputBinding', {
trigger: trigger.generic({
type: 'httpTrigger',
authLevel: 'anonymous',
methods: ['POST'],
route: "topic/{topicName}",
name: "req"
}),
return: daprPublishOutput,
handler: async (request, context) => {
context.log("Node HTTP trigger function processed a request.");
const payload = await request.text();
context.log(JSON.stringify(payload));
return { payload: 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 daprPublish:
{
"bindings":
{
"type": "daprPublish",
"direction": "out",
"name": "pubEvent",
"pubsubname": "%PubSubName%",
"topic": "B"
}
}
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
# Example to use Dapr Service Invocation Trigger and Dapr State Output binding to persist a new state into statestore
param (
$subEvent
)
Write-Host "PowerShell function processed a TransferEventBetweenTopics request from the Dapr Runtime."
# Convert the object to a JSON-formatted string with ConvertTo-Json
$jsonString = $subEvent["data"]
$messageFromTopicA = "Transfer from Topic A: $jsonString".Trim()
$publish_output_binding_req_body = @{
"payload" = $messageFromTopicA
}
# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name pubEvent -Value $publish_output_binding_req_body
次の例は、 v2 Python プログラミング モデルを使用する Dapr Publish 出力バインドを示しています。 Python 関数アプリ コードで daprPublish を使用するには:
import logging
import json
import azure.functions as func
app = func.FunctionApp()
@app.function_name(name="TransferEventBetweenTopics")
@app.dapr_topic_trigger(arg_name="subEvent", pub_sub_name="%PubSubName%", topic="A", route="A")
@app.dapr_publish_output(arg_name="pubEvent", pub_sub_name="%PubSubName%", topic="B")
def main(subEvent, pubEvent: func.Out[bytes]) -> None:
logging.info('Python function processed a TransferEventBetweenTopics request from the Dapr Runtime.')
subEvent_json = json.loads(subEvent)
payload = "Transfer from Topic A: " + str(subEvent_json["data"])
pubEvent.set(json.dumps({"payload": payload}).encode('utf-8'))
Attributes
In the in-process model, use the DaprPublish to define a Dapr publish output binding, which supports these parameters:
| function.json property | Description | Attribute を使って送信できる | RequestBody を使って送信できる |
|---|---|---|---|
| PubSubName | メッセージを送信する Dapr pub/sub の名前。 | ✔️ | ✔️ |
| Topic | メッセージを送信する Dapr トピックの名前。 | ✔️ | ✔️ |
| Payload | Required. 発行されるメッセージ。 | ❌ | ✔️ |
Annotations
DaprPublishOutput注釈を使用すると、発行されたメッセージに関数がアクセスできるようになります。
| Element | Description | Attribute を使って送信できる | RequestBody を使って送信できる |
|---|---|---|---|
| pubSubName | メッセージを送信する Dapr pub/sub の名前。 | ✔️ | ✔️ |
| topic | メッセージを送信する Dapr トピックの名前。 | ✔️ | ✔️ |
| payload | Required. 発行されるメッセージ。 | ❌ | ✔️ |
Configuration
次の表では、コードで設定するバインド構成プロパティについて説明します。
| Property | Description | Attribute を使って送信できる | RequestBody を使って送信できる |
|---|---|---|---|
| pubsubname | パブリッシャー コンポーネント サービスの名前。 | ✔️ | ✔️ |
| topic | 発行元トピックの名前/識別子。 | ✔️ | ✔️ |
| payload | Required. 発行されるメッセージ。 | ❌ | ✔️ |
The following table explains the binding configuration properties that you set in the function.json file.
| function.json property | Description | Attribute を使って送信できる | RequestBody を使って送信できる |
|---|---|---|---|
| pubsubname | パブリッシャー コンポーネント サービスの名前。 | ✔️ | ✔️ |
| topic | 発行元トピックの名前/識別子。 | ✔️ | ✔️ |
| payload | Required. 発行されるメッセージ。 | ❌ | ✔️ |
プロパティが Attributes と RequestBody の両方で定義されている場合は、RequestBody で指定されているデータが優先されます。
See the Example section for complete examples.
Usage
Dapr 発行出力バインドを使用するには、まず Dapr pub/sub コンポーネントを設定します。 使用するコンポーネントとその設定方法の詳細については、Dapr の公式ドキュメントを参照してください。
Python v2 で daprPublish を使用するには、正しい依存関係でプロジェクトを設定します。
requirements.textファイルに、次の行を追加します。azure-functions==1.18.0b3ターミナルで、Python ライブラリをインストールします。
pip install -r .\requirements.txt次の構成で
local.setting.jsonファイルを変更します。"PYTHON_ISOLATE_WORKER_DEPENDENCIES":1