Delen via


Status van aangepaste indeling in Durable Functions (Azure Functions)

Met aangepaste indelingsstatus kunt u een aangepaste statuswaarde instellen voor uw orchestratorfunctie. Deze status wordt opgegeven via de HTTP GetStatus-API of de equivalente SDK-API op het orchestration-clientobject.

Voorbeelden van toepassingsscenario’s

Voortgang visualiseren

Clients kunnen het eindpunt van de status peilen en een voortgangsgebruikersinterface weergeven die de huidige uitvoeringsfase visualiseert. In het volgende voorbeeld ziet u hoe de voortgang wordt gedeeld:

Notitie

Deze C#-voorbeelden zijn geschreven voor Durable Functions 2.x en zijn niet compatibel met Durable Functions 1.x. Zie het artikel Durable Functions versies voor meer informatie over de verschillen tussen versies.

[FunctionName("E1_HelloSequence")]
public static async Task<List<string>> Run(
    [OrchestrationTrigger] IDurableOrchestrationContext context)
{
    var outputs = new List<string>();

    outputs.Add(await context.CallActivityAsync<string>("E1_SayHello", "Tokyo"));
    context.SetCustomStatus("Tokyo");
    outputs.Add(await context.CallActivityAsync<string>("E1_SayHello", "Seattle"));
    context.SetCustomStatus("Seattle");
    outputs.Add(await context.CallActivityAsync<string>("E1_SayHello", "London"));
    context.SetCustomStatus("London");

    // returns ["Hello Tokyo!", "Hello Seattle!", "Hello London!"]
    return outputs;
}

[FunctionName("E1_SayHello")]
public static string SayHello([ActivityTrigger] string name)
{
    return $"Hello {name}!";
}

En vervolgens ontvangt de client de uitvoer van de indeling alleen wanneer CustomStatus het veld is ingesteld op 'Londen':

[FunctionName("HttpStart")]
public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Function, methods: "post", Route = "orchestrators/{functionName}")] HttpRequestMessage req,
    [DurableClient] IDurableOrchestrationClient starter,
    string functionName,
    ILogger log)
{
    // Function input comes from the request content.
    dynamic eventData = await req.Content.ReadAsAsync<object>();
    string instanceId = await starter.StartNewAsync(functionName, (string)eventData);

    log.LogInformation($"Started orchestration with ID = '{instanceId}'.");

    DurableOrchestrationStatus durableOrchestrationStatus = await starter.GetStatusAsync(instanceId);
    while (durableOrchestrationStatus.CustomStatus.ToString() != "London")
    {
        await Task.Delay(200);
        durableOrchestrationStatus = await starter.GetStatusAsync(instanceId);
    }

    HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent(JsonConvert.SerializeObject(durableOrchestrationStatus))
    };

    return httpResponseMessage;
  }
}

Aanpassing van uitvoer

Een ander interessant scenario is het segmenteren van gebruikers door aangepaste uitvoer te retourneren op basis van unieke kenmerken of interacties. Met behulp van de aangepaste indelingsstatus blijft de code aan de clientzijde algemeen. Alle belangrijkste wijzigingen vinden plaats aan de serverzijde, zoals wordt weergegeven in het volgende voorbeeld:

[FunctionName("CityRecommender")]
public static void Run(
  [OrchestrationTrigger] IDurableOrchestrationContext context)
{
  int userChoice = context.GetInput<int>();

  switch (userChoice)
  {
    case 1:
    context.SetCustomStatus(new
    {
      recommendedCities = new[] {"Tokyo", "Seattle"},
      recommendedSeasons = new[] {"Spring", "Summer"}
     });
      break;
    case 2:
      context.SetCustomStatus(new
      {
        recommendedCities = new[] {"Seattle, London"},
        recommendedSeasons = new[] {"Summer"}
      });
        break;
      case 3:
      context.SetCustomStatus(new
      {
        recommendedCities = new[] {"Tokyo, London"},
        recommendedSeasons = new[] {"Spring", "Summer"}
      });
        break;
  }

  // Wait for user selection and refine the recommendation
}

Instructiespecificatie

De orchestrator kan unieke instructies bieden aan de clients via de aangepaste status. De aangepaste statusinstructies worden toegewezen aan de stappen in de indelingscode:

[FunctionName("ReserveTicket")]
public static async Task<bool> Run(
  [OrchestrationTrigger] IDurableOrchestrationContext context)
{
  string userId = context.GetInput<string>();

  int discount = await context.CallActivityAsync<int>("CalculateDiscount", userId);

  context.SetCustomStatus(new
  {
    discount = discount,
    discountTimeout = 60,
    bookingUrl = "https://www.myawesomebookingweb.com",
  });

  bool isBookingConfirmed = await context.WaitForExternalEvent<bool>("BookingConfirmed");

  context.SetCustomStatus(isBookingConfirmed
    ? new {message = "Thank you for confirming your booking."}
    : new {message = "The booking was not confirmed on time. Please try again."});

  return isBookingConfirmed;
}

Query's uitvoeren op aangepaste status met HTTP

In het volgende voorbeeld ziet u hoe aangepaste statuswaarden kunnen worden opgevraagd met behulp van de ingebouwde HTTP-API's.

public static async Task SetStatusTest([OrchestrationTrigger] IDurableOrchestrationContext context)
{
    // ...do work...

    // update the status of the orchestration with some arbitrary data
    var customStatus = new { nextActions = new [] {"A", "B", "C"}, foo = 2, };
    context.SetCustomStatus(customStatus);

    // ...do more work...
}

Terwijl de indeling wordt uitgevoerd, kunnen externe clients deze aangepaste status ophalen:

GET /runtime/webhooks/durabletask/instances/instance123

Clients krijgen het volgende antwoord:

{
  "runtimeStatus": "Running",
  "input": null,
  "customStatus": { "nextActions": ["A", "B", "C"], "foo": 2 },
  "output": null,
  "createdTime": "2019-10-06T18:30:24Z",
  "lastUpdatedTime": "2019-10-06T19:40:30Z"
}

Waarschuwing

De nettolading van de aangepaste status is beperkt tot 16 KB aan UTF-16 JSON-tekst. We raden u aan externe opslag te gebruiken als u een grotere nettolading nodig hebt.

Volgende stappen