title
stringlengths
3
46
content
stringlengths
0
1.6k
21:525
21:526
Each task creates a different session scope so it can have a private copy of IDayStatistics, and then processes its request with statistics.Add.
21:527
That’s all! Now we need a source of purchase data to test our code. In the next subsection, we will create a fake microservice that randomly creates purchase data and passes it to the Counter gRPC service.
21:528
Testing the GrpcMicroservice project with a fake purchase requests generator
21:529
Let’s implement another microservice that feeds the previous microservice with randomly generated requests. The right project for a worker service that is not based on ASP.NET Core is the Worker Service project template. This project template automatically scaffolds a host containing a unique hosted service called Worker. We called this project FakeSource. In order to enable gRPC client usage, we must add the following NuGet packages: Google.Protobuf, Grpc.NET.Client, and Grpc.Tools.
21:530
Then, we must add the same counting.proto file as was added to the previous project. However, this time, we must require client code generation by placing the code below in the FakeSource project file:
21:531
<ItemGroup>
21:532
<Protobuf Include=`..GrpcMicroServiceProtoscounting.proto` GrpcServices=`Client`>
21:533
<Link>Protoscounting.proto</Link>
21:534
</Protobuf>
21:535
</ItemGroup>
21:536
21:537
The GrpcServices attribute set to Client is what enables client code generation instead of server code generation. The link tag appears since we added the same counting.proto file of the GrpcMicroService project as a link instead of copying it into the new project.
21:538
The hosted service is defined with the usual endless loop:
21:539
using Grpc.Net.Client;
21:540
using GrpcMicroService;
21:541
using Google.Protobuf.WellKnownTypes;
21:542
namespace FakeSource;
21:543
public class Worker : BackgroundService
21:544
{
21:545
private readonly string[] locations = new string[]
21:546
{ `Florence`, `London`, `New York`, `Paris` };
21:547
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
21:548
{
21:549
Random random = new Random();
21:550
while (!stoppingToken.IsCancellationRequested)
21:551
{
21:552
try
21:553
{
21:554
...
21:555
await Task.Delay(2000, stoppingToken);
21:556
}
21:557
catch (OperationCanceledException)
21:558
{
21:559
return;
21:560
}
21:561
catch { }
21:562
}
21:563
}
21:564
}
21:565
21:566
The locations array contains locations that will be randomly selected. As soon as the ExecuteAsync method starts, it creates the Random instance that will be used in all random generations.
21:567
Each loop is enclosed in a try/catch; if an OperationCanceledException is generated, the method exits, since a similar exception is created when the application is being shut down and the thread is killed. In the case of other exceptions, the code tries to recover by simply moving to the next loop. In an actual production application, the final catch should contain instructions to log the intercepted exception and/or instructions for a better recovery strategy. In the next example, we will see more sophisticated exception handling that is adequate for actual production applications.
21:568
Inside the try, the code creates a purchase message, sends it to the Counter service, and then sleeps for 2 seconds.
21:569
Below is the code that sends the requests:
21:570
var purchaseDay = new DateTimeOffset(DateTime.UtcNow.Date, TimeSpan.Zero);
21:571
//randomize a little bit purchase day
21:572
purchaseDay = purchaseDay.AddDays(random.Next(0, 3) - 1);
21:573
//message time
21:574
var now = DateTimeOffset.UtcNow;
21:575
//add random location
21:576
var location = locations[random.Next(0, locations.Length)];
21:577
var messageId = Guid.NewGuid().ToString();
21:578
//add random cost
21:579
int cost = 200 * random.Next(1, 4);
21:580
//send message
21:581
using var channel = GrpcChannel.ForAddress(`http://localhost:5000`);
21:582
var client = new Counter.CounterClient(channel);
21:583
//since this is a fake random source
21:584
//in case of errors we simply do nothing.
21:585
//An actual client should use Polly
21:586
//to define retry policies
21:587
try
21:588
{
21:589
await client.CountAsync(new CountingRequest
21:590
{
21:591
Id = messageId,
21:592
Location = location,
21:593
PurchaseTime = Timestamp.FromDateTimeOffset(purchaseDay),
21:594
Time = Timestamp.FromDateTimeOffset(now),
21:595
Cost = cost
21:596
});
21:597
21:598
}
21:599
catch {}
21:600
21:601
The code just prepares the message with random data; then, it creates a communication channel for the gRPC server address and passes it to the constructor of the Counter service proxy. Finally, the Count method is called on the proxy. The call is enclosed in a try/catch, and in the case of an error, the error is simply ignored, since we are just sending random data. Instead, an actual production application should use Polly to retry the communication with predefined strategies. Polly was described in the Resilient task execution section of Chapter 11, Applying a Microservice Architecture to Your Enterprise Application. We will show you how to use Polly in the example in the next section.
21:602
And there you have it! Now it is time to test everything. Right-click on the solution and select Set Startup Projects, then set both FakeSource and GrpcMicroService to start. This way, both projects will be launched simultaneously when the solution is run.
21:603
Launch Visual Studio and then let both processes run for a couple of minutes, then go to SQL Server Object Explorer and look for a database called grpcmicroservice. If the SQL Server Object Explorer window is not available in the left menu of Visual Studio, go to the top Window menu and select it.
21:604
Once you have located the database, show the content of the DayTotals and Purchases tables. You should see all computed daily sums and all processed purchases.
21:605
You can also inspect what happens in the server project by opening the HostedServices/ProcessPurchases.cs file and placing breakpoints on the queue.Top(10) and await queue.Dequeue(...) instructions.
21:606
You can also move FakeSource into a different Visual Studio solution so that you can simultaneously run several copies of FakeSource each in a different Visual Studio instance. It is also possible to double-click on the FakeSource project, which gives the option to save a new Visual Studio solution containing just a reference to the FakeSource project.
21:607
The full code is in the GrpcMicroService subfolder of the ch15 folder of the book’s GitHub repository. The next section shows you how to solve the same problem with queued communication using the RabbitMQ message broker.
21:608
A worker microservice based on RabbitMQ
21:609
This section explains the modifications needed to use a message broker instead of gRPC communication with an internal queue. This kind of solution is usually more difficult to test and design but allows for better horizontal scaling, and also enables extra features at almost no cost since they are offered by the message broker itself.
21:610
We assume that RabbitMQ has already been installed and adequately prepared, as explained in the Installing RabbitMQ core subsection of Chapter 14, Implementing Microservices with .NET.
21:611
First, the ASP.NET Core project must be replaced by another Worker Service project. Also, this project must add the connection string to its configuration file and must call the AddStorage extension method to add all the database services to the dependency injection engine. Below is the full content of the Program.cs file:
21:612
using GrpcMicroService.HostedServices;
21:613
using GrpcMicroServiceStore;
21:614
IHost host = Host.CreateDefaultBuilder(args)
21:615
.ConfigureServices((hostContext, services) =>
21:616
{
21:617
services.AddStorage(hostContext.Configuration
21:618
.GetConnectionString(`DefaultConnection`));
21:619
services.AddHostedService<ProcessPurchases>();
21:620
})
21:621
.Build();
21:622
await host.RunAsync();
21:623
21:624
We don’t need the gRPC services and service proxies anymore, just ProtoBuf for the binary messages, so both the FakeSource process and the GrpcMicroService projects must add just the Google.Protobuf and Grpc.Tools NuGet packages. Both projects need the following messages.proto file, which defines just the purchase message: