Skip to content

Azure function with Dapr to create event-driven, distributed applicationΒΆ

In this post we will integrate Azure function app to use Dapr system for pubsub messaging. Azure function could be either triggered by Event Hub or HttpTrigger. For simplicity we will test it with HttpTrigger. Project Repo

System DiagramΒΆ

alt

  • Azure function provides easier way to integrate with Event Hub
  • Dapr Subsystem hides complexity to deal with PubSub messaging

Getting ReadyΒΆ

Getting started with dapr See the dapr Azure Functions quickstart

Requirements

Note: Run Docker on WSL 2 on Windows for better experience

Install DaprΒΆ

Run in WSL window

PowerShell
wget -q https://raw.githubusercontent.com/dapr/cli/master/install/install.sh -O - | /bin/bash

Run to verify

PowerShell
dapr

Run init

PowerShell
dapr init

Verify Dapr version

PowerShell
dapr --version

Verify containers are running

PowerShell
docker ps

alt alt

Install dotnet sdk 3.1 and azure-functions-core-toolsΒΆ

Install dotnet sdk with azure function tools

Create Azure function AppΒΆ

Create a folder for a project or clone empty project from the gitΒΆ

PowerShell
dotnet new sln
func init process --dotnet --docker
dotnet sln azure-function-dapr.sln add ./process/process.csproj
cd process/
func new --name GetMessage --template "HTTP Trigger" --authlevel "anonymous"

ps@Dev-WD MINGW64 /c/Projects/azure-function-dapr/process (main)
$ func extensions install -p Dapr.AzureFunctions.Extension -v 0.12.0-p
review01
dotnet build process.csproj -o bin --no-incremental

To run/debug the function app locally click on "Initialize Project for Use with VS Code"

alt

Update the connection for the WebStorage and run/debug in VS Code

Add Nuget packagesΒΆ

  • Dapr.AzureFunctions.Extension
  • Microsoft.NET.Sdk.Functions
  • Microsoft.Azure.WebJobs.Extensions.EventHubs

Create Function GetMessage and add Dapr pubsubΒΆ

```csharp{19,34} using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Dapr.AzureFunctions.Extension; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json;

namespace process { public static class GetMessage { [FunctionName("GetMessage")] public static async Task Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, [DaprPublish(PubSubName = "pubsub", Topic = "alerts")] IAsyncCollector alertEvent, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request.");

Text Only
        string name = req.Query["name"];

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        string responseMessage = string.IsNullOrEmpty(name)
            ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            : $"Hello, {name}. This HTTP triggered function executed successfully.";

        await alertEvent.AddAsync(new DaprPubSubEvent(JsonConvert.SerializeObject(new { id = "testobj", message = "This is a test alert" })));

        return new OkObjectResult(responseMessage);
    }
}

} ```

Dapr config file config.yamlΒΆ

yaml apiVersion: dapr.io/v1alpha1 kind: Configuration metadata: name: daprConfig spec: tracing: samplingRate: '1' zipkin: endpointAddress: 'http://localhost:9411/api/v2/spans'

Add messagebus component /components/messagebus.yamlΒΆ

YAML
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: pubsub
spec:
  type: pubsub.redis
  metadata:
    - name: redisHost
      value: localhost:6379
    - name: redisPassword
      secretKeyRef:
        key: redis-password
        name: redis

Run Azure Function locallyΒΆ

PowerShell
dapr run -a functionapp -p 3001 --components-path ./components/ --config ./config.yaml -- func host start

Trigger Azure function from WSL consoleΒΆ

PowerShell
curl -X POST -H "Content-Type: application/json" -d '{ "name": "John Gray"}' http://172.21.132.136:7071/api/GetMessage

Validate if the message is in PubsubΒΆ

PowerShell
docker exec -it dapr_redis /bin/sh
keys *

It should return something like

PowerShell
1) "alerts"

Check actual messages

PowerShell
xread STREAMS alert 0

alt