Code Monkey home page Code Monkey logo

dnc-dapr-without-dotnet-sdk's Introduction

Dapr Pub-Sub with .NET Core Sample (without using Dapr Dotnet-SDK)

publisher-api-ci first-subscriber-api-ci second-subscriber-api-ci

This sample includes 3 .NET Core WebApi as below:

  • 1 publisher
    • Example.Dapr.Publisher
  • 2 subcribers:
    • Example.Dapr.FirstSubscriber will subscribe on ProductCreated topic
    • Example.Dapr.SecondSubscriber will subscribe on ProductCreated topic

Prerequisites

  1. Install Docker for Desktop
  2. Install Dapr Cli

How to deploy to Kubernetes

Run projects with Dapr Cli

  1. Starting Publisher

    cd .\source\Example.Dapr.Publisher\
    dapr run --app-id example-publisher --app-port 5000 dotnet run
  2. Starting FirstSubscriber

    cd .\source\Example.Dapr.FirstSubscriber\
    dapr run --app-id example-first-subscriber --app-port 5001 dotnet run
  3. Starting SecondSubscriber

    cd .\source\Example.Dapr.SecondSubscriber\
    dapr run --app-id example-second-subscriber --app-port 5002 dotnet run

Use the CLI to Publish Messages to Subscribers

dapr publish --topic ProductCreated --payload "{ \"ProductId\": 1, \"Code\":\"this-is-a-test\" }"

Both subscribers which are example-first-subscriber & example-second-subscriber receive a message

Logs of FirstSubscriber

Logs of SecondSubscriber

Use Visual Studio Code and RestClient extension to publish the message

Use RestClient Extension of Visual Studio Code

Notes

For Subscribers

  • Since we subscribe on ProductCreated topic, hence we have to define the endpoint as below
[HttpPost("ProductCreated")]
public IActionResult SubscribeProductCreated(CloudEvent request)
  • Remember add CloudEventJsonInputFormatter
services
    .AddControllers(opts =>
    {
        opts.InputFormatters.Insert(0, new CloudEventJsonInputFormatter());
    })
    .AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNameCaseInsensitive = true);
  • Then expose to Dapr runtime by define the MapGet inside Startup.cs
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapGet("/dapr/subscribe", async context =>
    {
        var channels = new[] { "ProductCreated" };
        var toJson = JsonSerializer.Serialize(channels);
        context.Response.ContentType = "application/json";
        await context.Response.WriteAsync(toJson);
    });
});

For Publisher

  • First, we define the DaprPublisher as Http Client in Startup.cs
services
    .AddHttpClient<DaprPublisher>((provider, client) =>
    {
        var logger = provider.GetRequiredService<ILogger<Startup>>();

        var daprPort = Environment.GetEnvironmentVariable("DAPR_HTTP_PORT") ?? "3500";

        var baseAddress = $"http://localhost:{daprPort}";

        logger.LogInformation($"[{nameof(Startup)}] - Publish Address: {baseAddress}");

        client.BaseAddress = new Uri(baseAddress, UriKind.Absolute);
    });
  • Then, in order to publish the message to ProductCreated topic, we just simply make a POST request to http://localhost:{DAPR_HTTP_PORT}/v1.0/publish/ProductCreated. See the code at DaprPublisher.cs

Give a Star! ⭐

If you liked this project or if it helped you, please give a star ⭐ for this repository. Thank you!!!

Resources

  1. Concepts of Publish/Subscribe Messaging
  2. Configure Redis
  3. Publish Topic
  4. Consume Topic
  5. Examples
  6. CloudEvent sdk-csharp

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.