- Notifications
You must be signed in to change notification settings - Fork1.3k
Distributed transaction solution in micro-service base on eventually consistency, also an eventbus with Outbox pattern
License
dotnetcore/CAP
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
CAP 中文
CAP is a library based on .Net standard, which is a solution to deal with distributed transactions, has the function of EventBus, it is lightweight, easy to use, and efficient.
In the process of building an SOA or MicroService system, we usually need to use the event to integrate each service. In the process, simple use of message queue does not guarantee reliability. CAP adopts local message table program integrated with the current database to solve exceptions that may occur in the process of the distributed system calling each other. It can ensure that the event messages are not lost in any case.
You can also use CAP as an EventBus. CAP provides a simpler way to implement event publishing and subscriptions. You do not need to inherit or implement any interface during subscription and sending process.
CAP implements the Outbox Pattern described in theeShop ebook.
CAP can be installed in your project with the following command.
PM> Install-Package DotNetCore.CAP
CAP supports most popular message queue as transport, following packages are available to install:
PM> Install-Package DotNetCore.CAP.KafkaPM> Install-Package DotNetCore.CAP.RabbitMQPM> Install-Package DotNetCore.CAP.AzureServiceBusPM> Install-Package DotNetCore.CAP.AmazonSQSPM> Install-Package DotNetCore.CAP.NATSPM> Install-Package DotNetCore.CAP.RedisStreamsPM> Install-Package DotNetCore.CAP.Pulsar
CAP supports most popular database as event storage, following packages are available to install:
// select a database provider you are using, event log table will integrate into.PM> Install-Package DotNetCore.CAP.SqlServerPM> Install-Package DotNetCore.CAP.MySqlPM> Install-Package DotNetCore.CAP.PostgreSqlPM> Install-Package DotNetCore.CAP.MongoDB //need MongoDB 4.0+ cluster
First, you need to configure CAP in your Startup.cs:
publicvoidConfigureServices(IServiceCollectionservices){//......services.AddDbContext<AppDbContext>();//Options, If you are using EF as the ORMservices.AddSingleton<IMongoClient>(newMongoClient(""));//Options, If you are using MongoDBservices.AddCap(x=>{// If you are using EF, you need to add the configuration:x.UseEntityFramework<AppDbContext>();//Options, Notice: You don't need to config x.UseSqlServer(""") again! CAP can autodiscovery.// If you are using ADO.NET, choose to add configuration you needed:x.UseSqlServer("Your ConnectionStrings");x.UseMySql("Your ConnectionStrings");x.UsePostgreSql("Your ConnectionStrings");// If you are using MongoDB, you need to add the configuration:x.UseMongoDB("Your ConnectionStrings");//MongoDB 4.0+ cluster// CAP support RabbitMQ,Kafka,AzureService as the MQ, choose to add configuration you needed:x.UseRabbitMQ("HostName");x.UseKafka("ConnectionString");x.UseAzureServiceBus("ConnectionString");x.UseAmazonSQS();});}
InjectICapPublisher
in your Controller, then use theICapPublisher
to send messages.
The version 7.0+ supports publish delay messages.
publicclassPublishController:Controller{privatereadonlyICapPublisher_capBus;publicPublishController(ICapPublishercapPublisher){_capBus=capPublisher;}[Route("~/adonet/transaction")]publicIActionResultAdonetWithTransaction(){using(varconnection=newMySqlConnection(ConnectionString)){using(vartransaction=connection.BeginTransaction(_capBus,autoCommit:true)){//your business logic code_capBus.Publish("xxx.services.show.time",DateTime.Now);// Publish delay message_capBus.PublishDelayAsync(TimeSpan.FromSeconds(delaySeconds),"xxx.services.show.time",DateTime.Now);}}returnOk();}[Route("~/ef/transaction")]publicIActionResultEntityFrameworkWithTransaction([FromServices]AppDbContextdbContext){using(vartrans=dbContext.Database.BeginTransaction(_capBus,autoCommit:true)){//your business logic code_capBus.Publish("xxx.services.show.time",DateTime.Now);}returnOk();}}
In Controller Action
Add the Attribute[CapSubscribe()]
on Action to subscribe to messages:
publicclassPublishController:Controller{[CapSubscribe("xxx.services.show.time")]publicvoidCheckReceivedMessage(DateTimedatetime){Console.WriteLine(datetime);}}
In Business Logic Service
If your subscription method is not in the Controller, then your subscribe class needs to implementICapSubscribe
interface:
namespaceBusinessCode.Service{publicinterfaceISubscriberService{voidCheckReceivedMessage(DateTimedatetime);}publicclassSubscriberService:ISubscriberService,ICapSubscribe{[CapSubscribe("xxx.services.show.time")]publicvoidCheckReceivedMessage(DateTimedatetime){}}}
Then register your class that implementsISubscriberService
in Startup.cs
publicvoidConfigureServices(IServiceCollectionservices){services.AddTransient<ISubscriberService,SubscriberService>();services.AddCap(x=>{//...});}
You are able to implement async subscription. Subscription's method should return Task and receive CancellationToken as parameter.
publicclassAsyncSubscriber:ICapSubscribe{[CapSubscribe("name")]publicasyncTaskProcessAsync(Messagemessage,CancellationTokencancellationToken){awaitSomeOperationAsync(message,cancellationToken);}}
To group topic subscriptions on class level you're able to define a subscription on a method as a partial. Subscriptions on the message queue will then be a combination of the topic defined on the class and the topic defined on the method. In the following example theCreate(..)
function will be invoked when receiving a message oncustomers.create
[CapSubscribe("customers")]publicclassCustomersSubscriberService:ICapSubscribe{[CapSubscribe("create",isPartial:true)]publicvoidCreate(Customercustomer){}}
The concept of a subscription group is similar to that of a consumer group in Kafka. it is the same as the broadcast mode in the message queue, which is used to process the same message between multiple different microservice instances.
When CAP startups, it will use the current assembly name as the default group name, if multiple same group subscribers subscribe to the same topic name, there is only one subscriber that can receive the message.Conversely, if subscribers are in different groups, they will all receive messages.
In the same application, you can specifyGroup
property to keep subscriptions in different subscribe groups:
[CapSubscribe("xxx.services.show.time",Group="group1")]publicvoidShowTime1(DateTimedatetime){}[CapSubscribe("xxx.services.show.time",Group="group2")]publicvoidShowTime2(DateTimedatetime){}
ShowTime1
andShowTime2
will be called at the same time.
BTW, You can specify the default group name in the configuration:
services.AddCap(x=>{x.DefaultGroup="default-group-name";});
CAP also provides dashboard pages, you can easily view messages that were sent and received. In addition, you can also view the message status in real time in the dashboard. Use the following command to install the Dashboard in your project.
PM> Install-Package DotNetCore.CAP.Dashboard
In the distributed environment, the dashboard built-in integratesConsul as a node discovery, while the realization of the gateway agent function, you can also easily view the node or other node data, It's like you are visiting local resources.
If your service is deployed in Kubernetes, please use our Kubernetes discovery package.
PM> Install-Package DotNetCore.CAP.Dashboard.K8s
The dashboard default address is:http://localhost:xxx/cap , you can configure relative path/cap
withx.UseDashboard(opt =>{ opt.MatchPath="/mycap"; })
.
One of the easiest ways to contribute is to participate in discussions and discuss issues. You can also contribute by submitting pull requests with code changes.
About
Distributed transaction solution in micro-service base on eventually consistency, also an eventbus with Outbox pattern