title
stringlengths 3
46
| content
stringlengths 0
1.6k
|
---|---|
21:324 | Figure 21.13: Execution results |
21:325 | The packages have been nested inside their destinations as required and Entity Framework Core creates a unique collection that has the same name as the DBContext class. |
21:326 | If you would like to continue experimenting with Cosmos DB development without wasting all your free Azure portal credit, you can install the Cosmos DB emulator, available at this link: https://aka.ms/cosmosdb-emulator. |
21:327 | Having learned how to choose the best options for data storage, we are in a position to start coding our first microservice. |
21:328 | A worker microservice with ASP.NET Core |
21:329 | In this section, we will show you how to implement a microservice that receives communications through gRPC and an internal queue based on a database table. The first subsection briefly describes the microservice specifications and the overall architecture. You are encouraged to review Chapter 14, Implementing Microservices with .NET, which contains all the theory behind this example. |
21:330 | The specifications and architecture |
21:331 | Our example microservice is required to compute the daily sums of all purchases. According to the data-driven approach, we suppose that all daily sums are pre-computed by receiving messages that are sent as soon as a new purchase is finalized. The purpose of the microservice is to maintain a database of all purchases and all daily sums that can be queried by an administrative user. We will implement just the functionalities needed to fill the two database tables. |
21:332 | The implementation described in this section is based on an ASP.NET Core application that hosts a gRPC service. The gRPC service simply fills a messages queue and immediately returns to avoid the sender remaining blocked for the whole time of the computation. |
21:333 | The actual processing is performed by an ASP.NET Core-hosted service declared in the dependency injection engine associated with the application host. The worker-hosted service executes an endless loop where it extracts N messages from the queue and passes them to N parallel threads that process them. |
21:334 | |
21:335 | Figure 21.14: gRPC microservice architecture |
21:336 | When the N messages are taken from the queue, they are not immediately removed but are simply marked with the extraction time. Since messages can only be extracted from the queue if their last extraction time is far enough ahead (say, a time T), no other worker thread can extract them again while they are being processed. When message processing is successfully completed, the message is removed from the queue. If the processing fails, no action is taken on the message, so the message remains blocked in the queue till the T interval expires, and then it can be picked up again by the worker thread. |
21:337 | The microservice can be scaled vertically by increasing the processor cores and the number N of threads. It can be scaled horizontally, too, by using a load balancer that splits the loads into several identical copies of the ASP.NET Core application. This kind of horizontal scaling increases the number of threads that can receive messages and the number of worker threads, but since all ASP.NET Core applications share the same database, it is limited by database performance. |
21:338 | The database layer is implemented in a separate DLL (Dynamic Link Library) and all functionalities are abstracted in two interfaces, one for interacting with the queue and another for adding a new purchase to the database. |
21:339 | The next subsection briefly describes the database layer. We will not give all the details since the main focus of the example is the microservice architecture and the communication technique. However, the full code is available in the ch15/GrpcMicroService folder of the GitHub repository associated with the book. |
21:340 | Having defined the overall architecture, let’s start with the storage layer code. |
21:341 | The storage layer |
21:342 | The storage layer is based on a database. It uses Entity Framework Core and is based on three entities with their associated tables: |
21:343 | |
21:344 | A QueueItem entity that represents a queue item |
21:345 | A Purchase entity that represents a single purchase |
21:346 | A DayTotal entity that represents the total of all purchases performed in a given day |
21:347 | |
21:348 | Below is a definition of the interface that manipulates the queue: |
21:349 | public interface IMessageQueue |
21:350 | { |
21:351 | public Task<IList<QueueItem>> Top(int n); |
21:352 | public Task Dequeue(IEnumerable<QueueItem> items); |
21:353 | public Task Enqueue(QueueItem item); |
21:354 | } |
21:355 | |
21:356 | Top extracts the N messages to pass to a maximum of N different threads. Enqueue adds a new message to the queue. Finally, Dequeue removes the items that have been successfully processed from the queue. |
21:357 | The interface that updates the purchase data is defined as shown below: |
21:358 | public interface IDayStatistics |
21:359 | { |
21:360 | Task<decimal> DayTotal(DateTimeOffset day); |
21:361 | Task<QueueItem?> Add(QueueItem model); |
21:362 | } |
21:363 | |
21:364 | Add adds a new purchase to the database. It returns the input queue item if the addition is successful, and null otherwise. DayTotal is a query method that returns a single day total. |
21:365 | The application layer communicates with the database layer through these two interfaces, through the three database entities, through the IUnitOfWork interface (which, as explained in the How data and domain layers communicate with other layers section of Chapter 13, Interacting with Data in C# – Entity Framework Core abstracts the DbContext), and through a dependency injection extension method like the one below: |
21:366 | public static class StorageExtensions |
21:367 | { |
21:368 | public static IServiceCollection AddStorage(this IServiceCollection services, |
21:369 | string connectionString) |
21:370 | { |
21:371 | services.AddDbContext<IUnitOfWork,MainDbContext>(options => |
21:372 | options.UseSqlServer(connectionString, b => |
21:373 | b.MigrationsAssembly(`GrpcMicroServiceStore`))); |
21:374 | services.AddScoped<IMessageQueue, MessageQueue>(); |
21:375 | services.AddScoped<IDayStatistics, DayStatistics>(); |
21:376 | return services; |
21:377 | } |
21:378 | } |
21:379 | |
21:380 | This method, which will be called in the application layer dependency injection definition, receives as input the database connection string and adds the DbContext abstracted with IUnitOfWork, with the two interfaces we defined before. |
21:381 | The database project, called GrpcMicroServiceStore, is contained in the ch15/GrpcMicroService folder of the GitHub repository associated with the book. It already contains all the necessary database migrations, so you can create the needed database with the steps below: |
21:382 | |
21:383 | In the Visual Studio Package Manager Console, select the GrpcMicroServiceStore project. |
21:384 | In Visual Studio Solution Explorer, right-click on the GrpcMicroServiceStore project and set it as the startup project. |
21:385 | In the Visual Studio Package Manager Console, issue the Update-Database command. |
21:386 | |
21:387 | Having a working storage layer, we can proceed with the microservices application layer. |
21:388 | The application layer |
21:389 | The application layer is an ASP.NET Core gRPC service project called GrpcMicroService. When the project is scaffolded by Visual Studio, it contains a .proto file in its Protos folder. This file needs to be deleted and replaced by a file called counting.proto, whose content must be as follows: |
21:390 | syntax = `proto3`; |
21:391 | option csharp_namespace = `GrpcMicroService`; |
21:392 | import `google/protobuf/timestamp.proto`; |
21:393 | package counting; |
21:394 | service Counter { |
21:395 | // Accepts a counting request |
21:396 | rpc Count (CountingRequest) returns (CountingReply); |
21:397 | } |
21:398 | message CountingRequest { |
21:399 | string id = 1; |
21:400 | google.protobuf.Timestamp time = 2; |
21:401 | string location = 3; |
21:402 | sint32 cost =4; |
21:403 | google.protobuf.Timestamp purchaseTime = 5; |
21:404 | }. |
21:405 | message CountingReply {} |
21:406 | |
21:407 | The above code defines the gRPC service with its input and output messages and the .NET namespace where you place them. We import the google/protobuf/timestamp.proto predefined .proto file because we need the TimeStamp type. The request contains purchase data, the time when the request message was created, and a unique message id that is used to force message idempotency. |
21:408 | In the database layer, the implementation of the IDayStatistics.Add method uses this id to verify if a purchase with the same id has already been processed, in which case it returns immediately: |
21:409 | bool processed = await ctx.Purchases.AnyAsync(m => m.Id == model.MessageId); |
21:410 | if (processed) return model; |
21:411 | |
21:412 | Automatic code generation for this file is enabled by replacing the existing protobuf XML tag with: |
21:413 | <Protobuf Include=`Protoscounting.proto` GrpcServices=`Server` /> |
21:414 | |
21:415 | The Grpc attribute set to `Server` enables server-side code generation. |
21:416 | In the Services project folder, the predefined gRPC service scaffolded by Visual Studio must be replaced with a file named CounterService.cs with the content below: |
21:417 | using Grpc.Core; |
21:418 | using GrpcMicroServiceStore; |
21:419 | namespace GrpcMicroService.Services; |
21:420 | public class CounterService: Counter.CounterBase |
21:421 | { |
21:422 | private readonly IMessageQueue queue; |
21:423 | public CounterService(IMessageQueue queue) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.