Durable Functions (Azure Functions) 中的單次協調器

對於背景作業,您通常必須確定特定的協調器一次只執行一個執行個體。 您可以在建立時,將特定執行個體識別碼指派給協調器,以確保 Durable Functions 這種單一行為。

單次個體範例

下列範例示範 HTTP 觸發程序函數如何建立單次背景作業協調流程。 程式碼可確保一個指定的執行個體識別碼只存在一個執行個體。

[FunctionName("HttpStartSingle")]
public static async Task<HttpResponseMessage> RunSingle(
    [HttpTrigger(AuthorizationLevel.Function, methods: "post", Route = "orchestrators/{functionName}/{instanceId}")] HttpRequestMessage req,
    [DurableClient] IDurableOrchestrationClient starter,
    string functionName,
    string instanceId,
    ILogger log)
{
    // Check if an instance with the specified ID already exists or an existing one stopped running(completed/failed/terminated).
    var existingInstance = await starter.GetStatusAsync(instanceId);
    if (existingInstance == null 
    || existingInstance.RuntimeStatus == OrchestrationRuntimeStatus.Completed 
    || existingInstance.RuntimeStatus == OrchestrationRuntimeStatus.Failed 
    || existingInstance.RuntimeStatus == OrchestrationRuntimeStatus.Terminated)
    {
        // An instance with the specified ID doesn't exist or an existing one stopped running, create one.
        dynamic eventData = await req.Content.ReadAsAsync<object>();
        await starter.StartNewAsync(functionName, instanceId, eventData);
        log.LogInformation($"Started orchestration with ID = '{instanceId}'.");
        return starter.CreateCheckStatusResponse(req, instanceId);
    }
    else
    {
        // An instance with the specified ID exists or an existing one still running, don't create one.
        return new HttpResponseMessage(HttpStatusCode.Conflict)
        {
            Content = new StringContent($"An instance with ID '{instanceId}' already exists."),
        };
    }
}

注意

先前的 C# 程式碼適用於 Durable Functions 2.x。 針對 Durable Functions 1.x,您必須使用 OrchestrationClient 屬性 (而非 DurableClient 屬性),而且必須使用 DurableOrchestrationClient 參數類型 (而非 IDurableOrchestrationClient)。 如需版本差異的詳細資訊,請參閱 Durable Functions 版本一文。

根據預設,執行個體識別碼是隨機產生的 GUID。 不過,在上述範例中,執行個體識別碼會從 URL 傳入路由資料。 然後,程式碼會擷取協調流程執行個體中繼資料,以檢查具有指定識別碼的執行個體是否已執行。 如果沒有執行這類執行個體,則會使用該識別碼建立新的執行個體。

注意

在此範例中有潛在的競爭條件。 如果 HttpStartSingle 的兩個實例同時執行,則兩個函式呼叫都將會報告成功,但現在只會實際啟動一個協調流程執行個體。 視您的需求而定,這可能會有非預期的副作用。

協調器函數的實作細節實際上不重要。 它可能是會啟動並完成的一般協調器函式,也可能是永遠執行的函式 (也就是永久性協調流程)。 重點是一次只有一個執行個體在執行。

下一步