Dapr 狀態輸出系結可讓您在函式執行期間將值儲存至 Dapr 狀態。
如需 Dapr 延伸模組的安裝和設定詳細資料,請參閱 Dapr 延伸模組概觀。
Example
您可以使用下列其中一種 C# 模式來建立 C# 函式:
| Execution model | Description |
|---|---|
| 隔離式工作者模型 | 您的函數程式碼在個別的 .NET 背景工作處理序中執行。 搭配 支援的 .NET 和 .NET Framework 版本使用。 若要深入瞭解,請參閱 隔離背景工作模型中執行 C# Azure Functions 的指南。 |
| In-process model | 您的函數程式碼執行的處理序與 Functions 主機處理序相同。 僅支援 .NET 的長期支援 (LTS) 版本。 若要深入瞭解,請參閱 使用 Azure Functions 開發 C# 類別庫函式。 |
下列範例示範如何使用 Dapr 狀態輸出系結,將新狀態保存至狀態存放區。
[FunctionName("StateOutputBinding")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "state/{key}")] HttpRequest req,
[DaprState("statestore", Key = "{key}")] IAsyncCollector<string> state,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
await state.AddAsync(requestBody);
return new OkResult();
}
下列範例會 "CreateNewOrderHttpTrigger" 使用 系 DaprStateOutput 結搭配 來建立函 HttpTrigger式:
@FunctionName("CreateNewOrderHttpTrigger")
public String run(
@HttpTrigger(
name = "req",
methods = {HttpMethod.POST},
authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage<Optional<String>> request,
@DaprStateOutput(
stateStore = "%StateStoreName%",
key = "product")
OutputBinding<String> product,
final ExecutionContext context) {
context.getLogger().info("Java HTTP trigger (CreateNewOrderHttpTrigger) processed a request.");
}
在下列範例中,Dapr 狀態輸出系結會與 對象註冊 app 的 HTTP 觸發程式配對:
const { app, trigger } = require('@azure/functions');
app.generic('StateOutputBinding', {
trigger: trigger.generic({
type: 'httpTrigger',
authLevel: 'anonymous',
methods: ['POST'],
route: "state/{key}",
name: "req"
}),
return: daprStateOutput,
handler: async (request, context) => {
context.log("Node HTTP trigger function processed a request.");
const payload = await request.text();
context.log(JSON.stringify(payload));
return { value : 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 daprState output:
{
"bindings":
{
"type": "daprState",
"stateStore": "%StateStoreName%",
"direction": "out",
"name": "order",
"key": "order"
}
}
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 函式應用程式程式碼中使用 daprState :
import logging
import json
import azure.functions as func
app = func.FunctionApp()
@app.function_name(name="HttpTriggerFunc")
@app.route(route="req", auth_level=dapp.auth_level.ANONYMOUS)
@app.dapr_state_output(arg_name="state", state_store="statestore", key="newOrder")
def main(req: func.HttpRequest, state: func.Out[str] ) -> str:
# request body must be passed this way '{\"value\": { \"key\": \"some value\" } }'
body = req.get_body()
if body is not None:
state.set(body.decode('utf-8'))
logging.info(body.decode('utf-8'))
else:
logging.info('req body is none')
return 'ok'
Attributes
In the in-process model, use the DaprState to define a Dapr state output binding, which supports these parameters:
| Parameter | Description | 可透過屬性傳送 | 可透過 RequestBody 傳送 |
|---|---|---|---|
| StateStore | 要儲存狀態的狀態存放區名稱。 | ✔️ | ❌ |
| Key | 在狀態存放區中儲存狀態的金鑰名稱。 | ✔️ | ✔️ |
| Value | Required. 要儲存的值。 | ❌ | ✔️ |
Annotations
批 DaprStateOutput 注可讓您函式存取狀態存放區。
| Element | Description | 可透過屬性傳送 | 可透過 RequestBody 傳送 |
|---|---|---|---|
| stateStore | 要儲存狀態的狀態存放區名稱。 | ✔️ | ❌ |
| key | 在狀態存放區中儲存狀態的金鑰名稱。 | ✔️ | ✔️ |
| value | Required. 要儲存的值。 | ❌ | ✔️ |
Configuration
下表說明您在程式碼中設定的繫結設定屬性。
| Property | Description | 可透過屬性傳送 | 可透過 RequestBody 傳送 |
|---|---|---|---|
| stateStore | 要儲存狀態的狀態存放區名稱。 | ✔️ | ❌ |
| key | 在狀態存放區中儲存狀態的金鑰名稱。 | ✔️ | ✔️ |
| value | Required. 要儲存的值。 | ❌ | ✔️ |
The following table explains the binding configuration properties that you set in the function.json file.
| function.json property | Description | 可透過屬性傳送 | 可透過 RequestBody 傳送 |
|---|---|---|---|
| stateStore | 要儲存狀態的狀態存放區名稱。 | ✔️ | ❌ |
| key | 在狀態存放區中儲存狀態的金鑰名稱。 | ✔️ | ✔️ |
| value | Required. 要儲存的值。 | ❌ | ✔️ |
如果屬性在 Attributes 和 RequestBody 中都有定義,則系統會優先考量 RequestBody 中提供的資料。
See the Example section for complete examples.
Usage
若要使用 Dapr 狀態輸出系結,請先設定 Dapr 狀態存放區元件。 您可以在官方 Dapr 文件中深入了解要使用哪個元件,以及如何進行設定。