Dapr in Action: A Simple Example to Get You Started 🚀
Hey, code ninjas! 🥷
In my last blog post, I talked about the powers of Dapr, the microservices sidekick that’s got your back. Now, it’s time to dive into a simple example that showcases some of Dapr’s coolest features. Ready to get your hands dirty? Let’s go! 💪
For this example, we’ll create a basic app with two microservices: one that generates a random number and another that squares it. We’ll use Dapr to handle service invocation and state management.
Step 1: Install DAPR 📦
First things first, make sure you have Dapr installed on your machine. You can find the installation instructions here: Dapr Getting Started.
Step 2: Create the Number Generator Service 🎲
Let’s start by creating a simple ASP.NET Core Web API service that generates a random number between 1 and 100:
// NumberGeneratorController.cs
using Microsoft.AspNetCore.Mvc;
namespace NumberGenerator.Controllers
{
[ApiController]
[Route("[controller]")]
public class NumberGeneratorController : ControllerBase
{
[HttpGet("generate")]
public ActionResult<int> GenerateNumber()
{
Random random = new Random();
int number = random.Next(1, 101);
return Ok(number);
}
}
}
Step 3: Create the Squaring Service 📐
Next, we’ll create another ASP.NET Core Web API service that takes a number and returns its square:
// SquaringServiceController.cs
using Microsoft.AspNetCore.Mvc;
namespace SquaringService.Controllers
{
[ApiController]
[Route("[controller]")]
public class SquaringServiceController : ControllerBase
{
[HttpPost("square")]
public ActionResult<int> SquareNumber([FromBody] int number)
{
int square = number * number;
return Ok(square);
}
}
}
Step 4: Running the Services with Dapr 🚀
To run these services with Dapr, open two separate terminals, navigate to the root folder of each service, and execute the following commands:
dapr run --app-id numbergenerator --app-port 7000 --dapr-http-port 3500 dotnet run
dapr run --app-id squaringservice --app-port 7001 dotnet run
Dapr will now take care of service discovery and invocation for you!
Step 5: Using Dapr’s State Management 🗄️
To store the generated number and its square, we’ll use Dapr’s state management. Create a new C# Console App that invokes both services and stores the results using Dapr’s state API:
// Program.cs
using System.Net.Http.Json;
namespace DaprExampleApp
{
class Program
{
static async Task Main(string[] args)
{
using var client = new HttpClient();
// Generate a random number using the number-generator service
var numberResponse = await client.GetAsync("http://localhost:3500/v1.0/invoke/numbergenerator/method/numbergenerator/generate");
int number = await numberResponse.Content.ReadFromJsonAsync<int>();
// Square the number using the squaring-service
var squareResponse = await client.PostAsJsonAsync("http://localhost:3500/v1.0/invoke/squaringservice/method/SquaringService/square", number);
int square = await squareResponse.Content.ReadFromJsonAsync<int>();
// Save the number and its square using Dapr's state management
var stateData = new[]
{
new { key = "number", value = number },
new { key = "square", value = square }
};
await client.PostAsJsonAsync("http://localhost:3500/v1.0/state/statestore", stateData);
Console.WriteLine($"Number: {number}, Square: {square}");
}
}
}
Step 6: Run and Enjoy! 🎉
With both microservices running, execute the Console App you created in Step 5. You should see the generated number and its square printed on the console.
There you have it! A simple C# example showcasing the power of Dapr. We’ve used Dapr to invoke our services and manage their state, making it easy to build and manage our microservices. Now it’s your turn to harness the power of Dapr in your own projects.
Happy coding! 🎉👩💻👨💻🚀