{"id":13429590,"url":"https://github.com/dotnetcore/CAP","last_synced_at":"2025-03-16T03:31:56.206Z","repository":{"id":37742799,"uuid":"76445704","full_name":"dotnetcore/CAP","owner":"dotnetcore","description":"Distributed transaction solution in micro-service base on eventually consistency, also an eventbus with Outbox pattern","archived":false,"fork":false,"pushed_at":"2024-12-05T11:37:45.000Z","size":13592,"stargazers_count":6736,"open_issues_count":12,"forks_count":1291,"subscribers_count":302,"default_branch":"master","last_synced_at":"2024-12-30T21:15:49.822Z","etag":null,"topics":["distributed-transactions","eventbus","kafka","microservices","outbox-pattern","rabbitmq","service-bus"],"latest_commit_sha":null,"homepage":"http://cap.dotnetcore.xyz","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dotnetcore.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":"code-of-conduct.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-12-14T09:40:20.000Z","updated_at":"2024-12-27T01:47:12.000Z","dependencies_parsed_at":"2023-10-12T09:20:32.836Z","dependency_job_id":"c9a42c52-c718-42eb-a8b2-72ca1e7312d7","html_url":"https://github.com/dotnetcore/CAP","commit_stats":{"total_commits":1905,"total_committers":112,"mean_commits":"17.008928571428573","dds":"0.12650918635170605","last_synced_commit":"e3cffd1e668aff48715a9c34ce147dbf213c3880"},"previous_names":[],"tags_count":77,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dotnetcore%2FCAP","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dotnetcore%2FCAP/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dotnetcore%2FCAP/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dotnetcore%2FCAP/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dotnetcore","download_url":"https://codeload.github.com/dotnetcore/CAP/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243822309,"owners_count":20353496,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["distributed-transactions","eventbus","kafka","microservices","outbox-pattern","rabbitmq","service-bus"],"created_at":"2024-07-31T02:00:42.203Z","updated_at":"2025-03-16T03:31:55.690Z","avatar_url":"https://github.com/dotnetcore.png","language":"C#","readme":"\u003cp align=\"center\"\u003e\n  \u003cimg height=\"140\" src=\"https://raw.githubusercontent.com/dotnetcore/CAP/master/docs/content/img/logo.svg\"\u003e\n\u003c/p\u003e\n\n# CAP 　　　　　　　　　　　　　　　　　　　　[中文](https://github.com/dotnetcore/CAP/blob/master/README.zh-cn.md)\n[![Docs\u0026Dashboard](https://github.com/dotnetcore/CAP/actions/workflows/deploy-docs-and-dashboard.yml/badge.svg?branch=master)](https://github.com/dotnetcore/CAP/actions/workflows/deploy-docs-and-dashboard.yml)\n[![AppVeyor](https://ci.appveyor.com/api/projects/status/v8gfh6pe2u2laqoa/branch/master?svg=true)](https://ci.appveyor.com/project/yang-xiaodong/cap/branch/master)\n[![NuGet](https://img.shields.io/nuget/v/DotNetCore.CAP.svg)](https://www.nuget.org/packages/DotNetCore.CAP/)\n[![NuGet Preview](https://img.shields.io/nuget/vpre/DotNetCore.CAP.svg?label=nuget-pre)](https://www.nuget.org/packages/DotNetCore.CAP/)\n[![Member project of .NET Core Community](https://img.shields.io/badge/member%20project%20of-NCC-9e20c9.svg)](https://github.com/dotnetcore)\n[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/dotnetcore/CAP/master/LICENSE.txt)\n\nCAP 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.\n\nIn 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.\n\nYou 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.\n\n## Architecture overview\n\n![cap.png](https://raw.githubusercontent.com/dotnetcore/CAP/master/docs/content/img/architecture-new.png)\n\n\u003e CAP implements the Outbox Pattern described in the [eShop ebook](https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/multi-container-microservice-net-applications/subscribe-events#designing-atomicity-and-resiliency-when-publishing-to-the-event-bus).\n\n## Getting Started\n\n### NuGet\n\nCAP can be installed in your project with the following command.\n\n```\nPM\u003e Install-Package DotNetCore.CAP\n```\n\nCAP supports most popular message queue as transport, following packages are available to install:\n\n```\nPM\u003e Install-Package DotNetCore.CAP.Kafka\nPM\u003e Install-Package DotNetCore.CAP.RabbitMQ\nPM\u003e Install-Package DotNetCore.CAP.AzureServiceBus\nPM\u003e Install-Package DotNetCore.CAP.AmazonSQS\nPM\u003e Install-Package DotNetCore.CAP.NATS\nPM\u003e Install-Package DotNetCore.CAP.RedisStreams\nPM\u003e Install-Package DotNetCore.CAP.Pulsar\n```\n\nCAP supports most popular database as event storage, following packages are available to install:\n\n```\n// select a database provider you are using, event log table will integrate into.\n\nPM\u003e Install-Package DotNetCore.CAP.SqlServer\nPM\u003e Install-Package DotNetCore.CAP.MySql\nPM\u003e Install-Package DotNetCore.CAP.PostgreSql\nPM\u003e Install-Package DotNetCore.CAP.MongoDB     //need MongoDB 4.0+ cluster\n```\n\n### Configuration\n\nFirst, you need to configure CAP in your Startup.cs：\n\n```cs\npublic void ConfigureServices(IServiceCollection services)\n{\n    //......\n\n    services.AddDbContext\u003cAppDbContext\u003e(); //Options, If you are using EF as the ORM\n    services.AddSingleton\u003cIMongoClient\u003e(new MongoClient(\"\")); //Options, If you are using MongoDB\n\n    services.AddCap(x =\u003e\n    {\n        // If you are using EF, you need to add the configuration：\n        x.UseEntityFramework\u003cAppDbContext\u003e(); //Options, Notice: You don't need to config x.UseSqlServer(\"\"\") again! CAP can autodiscovery.\n\n        // If you are using ADO.NET, choose to add configuration you needed：\n        x.UseSqlServer(\"Your ConnectionStrings\");\n        x.UseMySql(\"Your ConnectionStrings\");\n        x.UsePostgreSql(\"Your ConnectionStrings\");\n\n        // If you are using MongoDB, you need to add the configuration：\n        x.UseMongoDB(\"Your ConnectionStrings\");  //MongoDB 4.0+ cluster\n\n        // CAP support RabbitMQ,Kafka,AzureService as the MQ, choose to add configuration you needed：\n        x.UseRabbitMQ(\"HostName\");\n        x.UseKafka(\"ConnectionString\");\n        x.UseAzureServiceBus(\"ConnectionString\");\n        x.UseAmazonSQS();\n    });\n}\n\n```\n\n### Publish\n\nInject `ICapPublisher` in your Controller, then use the `ICapPublisher` to send messages.\n\n\u003e The version 7.0+ supports publish delay messages.\n\n```c#\npublic class PublishController : Controller\n{\n    private readonly ICapPublisher _capBus;\n\n    public PublishController(ICapPublisher capPublisher)\n    {\n        _capBus = capPublisher;\n    }\n\n    [Route(\"~/adonet/transaction\")]\n    public IActionResult AdonetWithTransaction()\n    {\n        using (var connection = new MySqlConnection(ConnectionString))\n        {\n            using (var transaction = connection.BeginTransaction(_capBus, autoCommit: true))\n            {\n                //your business logic code\n\n                _capBus.Publish(\"xxx.services.show.time\", DateTime.Now);\n\n                // Publish delay message\n                _capBus.PublishDelayAsync(TimeSpan.FromSeconds(delaySeconds), \"xxx.services.show.time\", DateTime.Now);\n            }\n        }\n\n        return Ok();\n    }\n\n    [Route(\"~/ef/transaction\")]\n    public IActionResult EntityFrameworkWithTransaction([FromServices]AppDbContext dbContext)\n    {\n        using (var trans = dbContext.Database.BeginTransaction(_capBus, autoCommit: true))\n        {\n            //your business logic code\n\n            _capBus.Publish(\"xxx.services.show.time\", DateTime.Now);\n        }\n\n        return Ok();\n    }\n}\n\n```\n\n### Subscribe\n\n**In Controller Action**\n\nAdd the Attribute `[CapSubscribe()]` on Action to subscribe to messages:\n\n```c#\npublic class PublishController : Controller\n{\n    [CapSubscribe(\"xxx.services.show.time\")]\n    public void CheckReceivedMessage(DateTime datetime)\n    {\n        Console.WriteLine(datetime);\n    }\n}\n\n```\n\n**In Business Logic Service**\n\nIf your subscription method is not in the Controller, then your subscribe class needs to implement `ICapSubscribe` interface:\n\n```c#\n\nnamespace BusinessCode.Service\n{\n    public interface ISubscriberService\n    {\n        void CheckReceivedMessage(DateTime datetime);\n    }\n\n    public class SubscriberService: ISubscriberService, ICapSubscribe\n    {\n        [CapSubscribe(\"xxx.services.show.time\")]\n        public void CheckReceivedMessage(DateTime datetime)\n        {\n        }\n    }\n}\n\n```\n\nThen register your class that implements `ISubscriberService` in Startup.cs\n\n```c#\npublic void ConfigureServices(IServiceCollection services)\n{\n    services.AddTransient\u003cISubscriberService,SubscriberService\u003e();\n\n    services.AddCap(x=\u003e\n    {\n        //...\n    });\n}\n```\n#### Async subscription\n\nYou are able to implement async subscription. Subscription's method should return Task and receive CancellationToken as parameter.\n\n```c#\npublic class AsyncSubscriber : ICapSubscribe\n{\n    [CapSubscribe(\"name\")]\n    public async Task ProcessAsync(Message message, CancellationToken cancellationToken)\n    {\n        await SomeOperationAsync(message, cancellationToken);\n    }\n}\n```\n#### Use partials for topic subscriptions\n\nTo 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 the `Create(..)` function will be invoked when receiving a message on `customers.create`\n\n```c#\n[CapSubscribe(\"customers\")]\npublic class CustomersSubscriberService : ICapSubscribe\n{\n    [CapSubscribe(\"create\", isPartial: true)]\n    public void Create(Customer customer)\n    {\n    }\n}\n```\n\n#### Subscribe Group\n\nThe 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.\n\nWhen 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.\nConversely, if subscribers are in different groups, they will all receive messages.\n\nIn the same application, you can specify `Group` property to keep subscriptions in different subscribe groups:\n\n```C#\n\n[CapSubscribe(\"xxx.services.show.time\", Group = \"group1\" )]\npublic void ShowTime1(DateTime datetime)\n{\n}\n\n[CapSubscribe(\"xxx.services.show.time\", Group = \"group2\")]\npublic void ShowTime2(DateTime datetime)\n{\n}\n\n```\n`ShowTime1` and `ShowTime2` will be called at the same time.\n\nBTW, You can specify the default group name in the configuration:\n\n```C#\nservices.AddCap(x =\u003e\n{\n    x.DefaultGroup = \"default-group-name\";  \n});\n\n```\n\n### Dashboard\n\nCAP 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.\n\n```\nPM\u003e Install-Package DotNetCore.CAP.Dashboard\n```\n\nIn the distributed environment, the dashboard built-in integrates [Consul](http://consul.io) 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.\n\n[View Consul config docs](https://cap.dotnetcore.xyz/user-guide/en/monitoring/consul)\n\nIf your service is deployed in Kubernetes, please use our Kubernetes discovery package.\n\n```\nPM\u003e Install-Package DotNetCore.CAP.Dashboard.K8s\n```\n\n[View Kubernetes config docs](https://cap.dotnetcore.xyz/user-guide/en/monitoring/kubernetes/)\n\nThe dashboard default address is: [http://localhost:xxx/cap](http://localhost:xxx/cap) , you can configure relative path `/cap` with `x.UseDashboard(opt =\u003e{ opt.MatchPath=\"/mycap\"; })`.\n\n\n## Contribute\n\nOne 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.\n\n### License\n\n[MIT](https://github.com/dotnetcore/CAP/blob/master/LICENSE.txt)\n","funding_links":[],"categories":["Frameworks, Libraries and Tools","Tools and Libraries","others","框架, 库和工具","Event/Message \u0026 Service Bus","C# #","transaction","Queue","队列","Architectural Patterns","Identifiers"],"sub_categories":["Application Frameworks","Messaging","应用程序框架","GUI - other","Microservices"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdotnetcore%2FCAP","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdotnetcore%2FCAP","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdotnetcore%2FCAP/lists"}