Quickstart: Een JavaScript-Durable Functions-app maken

Gebruik Durable Functions, een functie van Azure Functions, om stateful serverloze werkstromen te schrijven in JavaScript. In deze quickstart kloont en voert u een voorbeeldtoepassing uit die twee veelvoorkomende orchestratiepatronen demonstreert:

  • Functiekoppeling: Roept activiteiten opeenvolgend aan (Tokio → Seattle → Londen).
  • Fan-out/fan-in: roept activiteiten parallel aan in vijf steden en voegt vervolgens de resultaten samen.

Aan het einde hebt u beide orchestraties lokaal draaien met de Durable Task Scheduler emulator en kunt u hun status bekijken op het dashboard.

  • Kloon en bereid het Hello Cities-voorbeeldproject voor.
  • Stel de Durable Task Scheduler emulator en Azurite in voor lokale ontwikkeling.
  • Voer de function app uit en start beide orchestraties.
  • Controleer de orchestratiestatus en uitvoer in het dashboard van Durable Task Scheduler.

Prerequisites

De emulator voor Durable Task Scheduler instellen

De Durable Task Scheduler-emulator biedt een lokale ontwikkelomgeving, zodat u indelingen kunt testen zonder een Azure abonnement. De Functions-host vereist ook Azurite voor lokale opslag.

Start beide containers op:

docker run -d --name dtsemulator -p 8080:8080 -p 8082:8082 \
  mcr.microsoft.com/dts/dts-emulator:latest

docker run -d --name azurite -p 10000:10000 -p 10001:10001 -p 10002:10002 \
  mcr.microsoft.com/azure-storage/azurite

Tip

Zodra de emulator actief is, kunt u het Durable Task Scheduler-dashboard openen op http://localhost:8082 om orchestraties te bewaken.

Het snelstartvoorbeeld uitvoeren

  1. Navigeer naar de voorbeeldmap Hello Cities:

    cd samples/durable-functions/javascript/HelloCities
    
  2. Afhankelijkheden installeren:

    npm install
    
  3. Controleer of het local.settings.json bestand de volgende configuratie bevat:

    {
      "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "node",
        "DURABLE_TASK_SCHEDULER_CONNECTION_STRING": "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None"
      }
    }
    
  4. Start de functie-app:

    func start
    
  5. Start in een afzonderlijke terminal de function chaining-orkestratie:

    $response = Invoke-RestMethod -Method POST -Uri http://localhost:7071/api/StartChaining
    $response
    

    Het antwoord bevat status-URL's voor de orchestratie-instantie. Kopieer de statusQueryGetUri-waarde en voer deze uit om het resultaat te controleren:

    Invoke-RestMethod -Uri $response.statusQueryGetUri
    
  6. Start de fan-out/fan-in-orchestratie:

    $response = Invoke-RestMethod -Method POST -Uri http://localhost:7071/api/StartFanOutFanIn
    Invoke-RestMethod -Uri $response.statusQueryGetUri
    

Verwachte uitvoer

De POST-aanvraag retourneert een JSON-antwoord met status-URL's. Voorbeeld:

{
  "id": "<instanceId>",
  "statusQueryGetUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/<instanceId>?code=...",
  "sendEventPostUri": "...",
  "terminatePostUri": "...",
  "purgeHistoryDeleteUri": "..."
}

Wanneer u statusQueryGetUri opvraagt en de runtimeStatus van de orchestratie Completed is, kunt u de resultaten van de begroeting in het veld output vinden. De ketenorkestratie geeft terug:

{
  "name": "chainingOrchestration",
  "runtimeStatus": "Completed",
  "output": ["Hello Tokyo!", "Hello Seattle!", "Hello London!"]
}

De fan-out/fan-in-orchestratie geeft het volgende terug:

{
  "name": "fanOutFanInOrchestration",
  "runtimeStatus": "Completed",
  "output": ["Hello Tokyo!", "Hello Seattle!", "Hello London!", "Hello Paris!", "Hello Berlin!"]
}

Tip

Als runtimeStatusRunning of Pending weergeeft, wacht dan even en voer de query voor statusQueryGetUri opnieuw uit.

Open het dashboard van Durable Task Scheduler op http://localhost:8082 om de orchestratiestatus en uitvoeringsgeschiedenis te bekijken.

De code begrijpen

In het voorbeeld wordt het Node.js v4-programmeermodel gebruikt, waarbij alle functies in één bestand (src/functions/helloCities.js) zijn gedefinieerd.

Activiteitsfunctie

De sayHello activiteit heeft een plaatsnaam en retourneert een begroeting:

df.app.activity("sayHello", {
  handler: (city) => {
    return `Hello ${city}!`;
  },
});

Orchestratorfuncties

De chaining orchestrator roept sayHello opeenvolgend aan voor drie steden:

df.app.orchestration("chainingOrchestration", function* (context) {
  const outputs = [];
  outputs.push(yield context.df.callActivity("sayHello", "Tokyo"));
  outputs.push(yield context.df.callActivity("sayHello", "Seattle"));
  outputs.push(yield context.df.callActivity("sayHello", "London"));
  return outputs;
});

De fan-out/fan-in orchestrator plant activiteiten parallel:

df.app.orchestration("fanOutFanInOrchestration", function* (context) {
  const cities = ["Tokyo", "Seattle", "London", "Paris", "Berlin"];

  // Fan-out: schedule all activities in parallel
  const tasks = cities.map((city) => context.df.callActivity("sayHello", city));

  // Fan-in: wait for all to complete
  const results = yield context.df.Task.all(tasks);
  return results;
});

Clientfuncties

Door HTTP geactiveerde clientfuncties starten elke orchestratie. Bijvoorbeeld de koppelingsstarter:

app.http("StartChaining", {
  route: "StartChaining",
  methods: ["POST"],
  authLevel: "anonymous",
  extraInputs: [df.input.durableClient()],
  handler: async (request, context) => {
    const client = df.getClient(context);
    const instanceId = await client.startNew("chainingOrchestration");
    context.log(`Started chaining orchestration with ID = '${instanceId}'.`);
    return client.createCheckStatusResponse(request, instanceId);
  },
});

Configuratie

In het voorbeeld wordt de Durable Task Scheduler-emulator gebruikt als de back-end voor opslag. Dit is geconfigureerd in host.json:

{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "DurableTask.Core": "Warning"
    }
  },
  "extensions": {
    "durableTask": {
      "hubName": "default",
      "storageProvider": {
        "type": "azureManaged",
        "connectionStringName": "DURABLE_TASK_SCHEDULER_CONNECTION_STRING"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  }
}

De hulpbronnen opschonen

Stop de emulatorcontainers wanneer u klaar bent:

docker stop dtsemulator azurite && docker rm dtsemulator azurite

Volgende stappen