What is cap?
CAP is a set of solutions for distributed transactions developed by the Yang Xiaodong God in our garden, the first thousand-Star project in. Net Core community (now 1656 Star), lightweight, easy to use, and high performance.
Github.com/dotnetcore/cap
This blog is focused on ease of use, the narrative, together to see how the cap combined with EF core and RABBITMQ lead small white easily into the world of distributed Message Queuing.
Get ready
First of all, you need to build a set of RABBITMQ system, the construction process is not described here, if you feel trouble, you can use my good.
HostName: coderayu.cn username:guest password:guest (can only be used as an experiment, data loss is not responsible)
Create an ASP. NET Core project and introduce a NuGet package
You can install the CAP in your project by running the following command.
Pm> Install-package Dotnetcore.cap
If your message queue is using Kafka, you can:
Pm> Install-package DotNetCore.CAP.Kafka
If your message queue is using RabbitMQ, you can:
Pm> Install-package DotNetCore.CAP.RabbitMQ
The CAP provides an extension of SQL Server, MYSQL, PostgreSQL as a database store:
// choose to install the database you are using on Demand Pm> install-PackageDotNetCore.CAP.SqlServerPM> install-packageDotNetCore.CAP.MySqlPM> Install-package DOTNETCORE.CAP.POSTGRESQL
Create DbContext
Because I'm using EF Core, I'll start by creating a DbContext context with the following code:
Public class Capdbcontext:dbcontext { publicbase(options) { } }
Startup configuration
The first step is to inject the related services in the Configureservices function, and the corresponding operations and functions are explained as follows:
Public voidconfigureservices (iservicecollection services) {//Inject DbContext context, if using MySQL may also need to add POMELO.ENTITYFRAMEWORKCORE.MYSQL this NuGet packageServices. adddbcontext<capdbcontext> (options =options. Usemysql ("Server=127.0.0.1;database=testcap; Userid=root; password=123456;")); //Configuring CapsServices. Addcap (x ={x.useentityframework<CapDbContext>(); //enable the operator panelX.usedashboard (); //using RABBITMQX.USERABBITMQ (RB = { //RABBITMQ Server AddressRb. HostName ="coderayu.cn"; Rb. UserName="Guest"; Rb. Password="Guest"; //Specifies the topic Exchange name, which is not specified with the defaultRb. Exchangename ="Cap.text.exchange"; }); //Set the time (in seconds) for the data to be stored in the database for successful processing, and the data will be cleaned up periodically to ensure the system is new. X.succeedmessageexpiredafter = -*3600; //set the number of failed retriesX.failedretrycount =5; }); Services. Addmvc (). Setcompatibilityversion (Compatibilityversion.version_2_1); }
And finally, we're going to congiure. Enable Cap Middleware
Public void Configure (Iapplicationbuilder app, ihostingenvironment env) { if (env. Isdevelopment ()) { app. Usedeveloperexceptionpage (); } // enable the CAP middleware app. Usecap (); App. Usemvc (); }
Build a CAP database with EF core
In the Package management console, enter the following command line
Pm> add-migration Init
Pm> Update-database
If executed successfully, open the database and you will see a table for storing the data sent and received by the CAP.
The meanings of each column in the table are as follows:
Sending and subscribing to messages
We valuescontroller directly on the basis of the transformation.
Inject in Controller ICapPublisher
and then use ICapPublisher
to send messages
Private ReadOnly icappublisher _publisher; Public Valuescontroller (icappublisher publisher) { = publisher; }
Send Message
[HttpGet] Public string Get (string message ) { //"Cap.test.queue" is a message sent Routekey, which can be understood as the name of the message pipeline _publisher. Publish ("cap.test.queue", message); return " sent successfully " ; }
Subscribe to Messages
//"Cap.test.queue" for Rautekey when sending messages, can also Blur match // details https:// www.rabbitmq.com/tutorials/tutorial-four-dotnet.html [Capsubscribe ("cap.test.queue")] Public void Handlemessage (string message) { Console.Write (DateTime.Now.ToString ()+" received message:"+message); }
Run
After starting the program, see that the CAP starts successfully
Immediately thereafter, the consumer is our subscription method registered successfully on the RABBITMQ server.
Send message, sent successfully, as follows
Once sent, the results of the subscription method output are immediately visible in the console.
Failed retry of message
In the subscription method, if an exception is thrown, the CAP considers the message processing to fail, automatically retries, and the number of retries is configured in the front.
We make a change to the subscription method, print the received information to the console, and throw an exception
//"Cap.test.queue" is a rautekey when sending a message, or it can be fuzzy matched//Details https://www.rabbitmq.com/tutorials/tutorial-four-dotnet.html[Capsubscribe ("Cap.test.queue")] Public voidHandlemessage (stringmessage) {Console.WriteLine (DateTime.Now.ToString ()+"Receive message:"+message); Throw NewException ("Test Failed retry"); }
As you can see, three retries are made immediately.
But in front of us, we set the number of failed retries to 5 times, why do we only retry three times? Do you want to call Xiao Dong to change the bug? Of course not.
It is observed that the first three times of the cap retries are immediate, and the subsequent retries are made every once in a while, when in the process of distributed communication, there may be problems that do not fix immediately, and it may take some time before the system recovers automatically, such as network jitter.
CAP instrument panel
Sent successfully five messages, successfully received processing three, two processing failed, processing failed tasks, we can directly in the Panel to re-consumption, it is very convenient.
At the same time, when processing a failed message, click the number of the message to see the contents of the message and the reason for the exception.
The cap is so powerful that it allows Message Queuing to operate so easily on a large product, learns the cap, and can boast that I also know about distributed task processing.
Thanks to Xiao Dong for developing such a powerful project while thanking. Net Core Community.
Reference CAP Github Wiki
Github.com/dotnetcore/cap/wiki
This blog demo code