You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 9.7 KiB

5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
7 years ago
5 years ago
5 years ago
2 years ago
4 years ago
2 years ago
2 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
4 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
3 years ago
4 years ago
4 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. <p align="center">
  2. <img height="140" src="https://cap.dotnetcore.xyz/img/logo.svg">
  3. </p>
  4. # CAP                     [中文](https://github.com/dotnetcore/CAP/blob/master/README.zh-cn.md)
  5. [![Travis branch](https://img.shields.io/travis/dotnetcore/CAP/master.svg?label=travis-ci)](https://travis-ci.org/dotnetcore/CAP)
  6. [![AppVeyor](https://ci.appveyor.com/api/projects/status/v8gfh6pe2u2laqoa/branch/master?svg=true)](https://ci.appveyor.com/project/yang-xiaodong/cap/branch/master)
  7. [![NuGet](https://img.shields.io/nuget/v/DotNetCore.CAP.svg)](https://www.nuget.org/packages/DotNetCore.CAP/)
  8. [![NuGet Preview](https://img.shields.io/nuget/vpre/DotNetCore.CAP.svg?label=nuget-pre)](https://www.nuget.org/packages/DotNetCore.CAP/)
  9. [![Member project of .NET Core Community](https://img.shields.io/badge/member%20project%20of-NCC-9e20c9.svg)](https://github.com/dotnetcore)
  10. [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/dotnetcore/CAP/master/LICENSE.txt)
  11. 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.
  12. 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.
  13. 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.
  14. ## Architecture overview
  15. ![cap.png](https://cap.dotnetcore.xyz/img/architecture-new.png)
  16. > 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).
  17. ## Getting Started
  18. ### NuGet
  19. CAP can be installed in your project with the following command.
  20. ```
  21. PM> Install-Package DotNetCore.CAP
  22. ```
  23. CAP supports most popular message queue as transport, following packages are available to install:
  24. ```
  25. PM> Install-Package DotNetCore.CAP.Kafka
  26. PM> Install-Package DotNetCore.CAP.RabbitMQ
  27. PM> Install-Package DotNetCore.CAP.AzureServiceBus
  28. PM> Install-Package DotNetCore.CAP.AmazonSQS
  29. PM> Install-Package DotNetCore.CAP.NATS
  30. PM> Install-Package DotNetCore.CAP.RedisStreams
  31. PM> Install-Package DotNetCore.CAP.Pulsar
  32. ```
  33. CAP supports most popular database as event storage, following packages are available to install:
  34. ```
  35. // select a database provider you are using, event log table will integrate into.
  36. PM> Install-Package DotNetCore.CAP.SqlServer
  37. PM> Install-Package DotNetCore.CAP.MySql
  38. PM> Install-Package DotNetCore.CAP.PostgreSql
  39. PM> Install-Package DotNetCore.CAP.MongoDB //need MongoDB 4.0+ cluster
  40. ```
  41. ### Configuration
  42. First, you need to configure CAP in your Startup.cs:
  43. ```cs
  44. public void ConfigureServices(IServiceCollection services)
  45. {
  46. //......
  47. services.AddDbContext<AppDbContext>(); //Options, If you are using EF as the ORM
  48. services.AddSingleton<IMongoClient>(new MongoClient("")); //Options, If you are using MongoDB
  49. services.AddCap(x =>
  50. {
  51. // If you are using EF, you need to add the configuration:
  52. x.UseEntityFramework<AppDbContext>(); //Options, Notice: You don't need to config x.UseSqlServer(""") again! CAP can autodiscovery.
  53. // If you are using ADO.NET, choose to add configuration you needed:
  54. x.UseSqlServer("Your ConnectionStrings");
  55. x.UseMySql("Your ConnectionStrings");
  56. x.UsePostgreSql("Your ConnectionStrings");
  57. // If you are using MongoDB, you need to add the configuration:
  58. x.UseMongoDB("Your ConnectionStrings"); //MongoDB 4.0+ cluster
  59. // CAP support RabbitMQ,Kafka,AzureService as the MQ, choose to add configuration you needed:
  60. x.UseRabbitMQ("ConnectionString");
  61. x.UseKafka("ConnectionString");
  62. x.UseAzureServiceBus("ConnectionString");
  63. x.UseAmazonSQS();
  64. });
  65. }
  66. ```
  67. ### Publish
  68. Inject `ICapPublisher` in your Controller, then use the `ICapPublisher` to send messages
  69. ```c#
  70. public class PublishController : Controller
  71. {
  72. private readonly ICapPublisher _capBus;
  73. public PublishController(ICapPublisher capPublisher)
  74. {
  75. _capBus = capPublisher;
  76. }
  77. [Route("~/adonet/transaction")]
  78. public IActionResult AdonetWithTransaction()
  79. {
  80. using (var connection = new MySqlConnection(ConnectionString))
  81. {
  82. using (var transaction = connection.BeginTransaction(_capBus, autoCommit: true))
  83. {
  84. //your business logic code
  85. _capBus.Publish("xxx.services.show.time", DateTime.Now);
  86. }
  87. }
  88. return Ok();
  89. }
  90. [Route("~/ef/transaction")]
  91. public IActionResult EntityFrameworkWithTransaction([FromServices]AppDbContext dbContext)
  92. {
  93. using (var trans = dbContext.Database.BeginTransaction(_capBus, autoCommit: true))
  94. {
  95. //your business logic code
  96. _capBus.Publish("xxx.services.show.time", DateTime.Now);
  97. }
  98. return Ok();
  99. }
  100. }
  101. ```
  102. ### Subscribe
  103. **In Controller Action**
  104. Add the Attribute `[CapSubscribe()]` on Action to subscribe to messages:
  105. ```c#
  106. public class PublishController : Controller
  107. {
  108. [CapSubscribe("xxx.services.show.time")]
  109. public void CheckReceivedMessage(DateTime datetime)
  110. {
  111. Console.WriteLine(datetime);
  112. }
  113. }
  114. ```
  115. **In Business Logic Service**
  116. If your subscription method is not in the Controller, then your subscribe class needs to implement `ICapSubscribe` interface:
  117. ```c#
  118. namespace BusinessCode.Service
  119. {
  120. public interface ISubscriberService
  121. {
  122. void CheckReceivedMessage(DateTime datetime);
  123. }
  124. public class SubscriberService: ISubscriberService, ICapSubscribe
  125. {
  126. [CapSubscribe("xxx.services.show.time")]
  127. public void CheckReceivedMessage(DateTime datetime)
  128. {
  129. }
  130. }
  131. }
  132. ```
  133. Then register your class that implements `ISubscriberService` in Startup.cs
  134. ```c#
  135. public void ConfigureServices(IServiceCollection services)
  136. {
  137. services.AddTransient<ISubscriberService,SubscriberService>();
  138. services.AddCap(x=>
  139. {
  140. //...
  141. });
  142. }
  143. ```
  144. #### Use partials for topic subscriptions
  145. 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 the `Create(..)` function will be invoked when receiving a message on `customers.create`
  146. ```c#
  147. [CapSubscribe("customers")]
  148. public class CustomersSubscriberService : ICapSubscribe
  149. {
  150. [CapSubscribe("create", isPartial: true)]
  151. public void Create(Customer customer)
  152. {
  153. }
  154. }
  155. ```
  156. #### Subscribe Group
  157. 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.
  158. 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.
  159. Conversely, if subscribers are in different groups, they will all receive messages.
  160. In the same application, you can specify `Group` property to keep subscriptions in different subscribe groups:
  161. ```C#
  162. [CapSubscribe("xxx.services.show.time", Group = "group1" )]
  163. public void ShowTime1(DateTime datetime)
  164. {
  165. }
  166. [CapSubscribe("xxx.services.show.time", Group = "group2")]
  167. public void ShowTime2(DateTime datetime)
  168. {
  169. }
  170. ```
  171. `ShowTime1` and `ShowTime2` will be called one after another because all received messages are processed linear.
  172. You can change that behaviour increasing `ConsumerThreadCount`.
  173. BTW, You can specify the default group name in the configuration:
  174. ```C#
  175. services.AddCap(x =>
  176. {
  177. x.DefaultGroup = "default-group-name";
  178. });
  179. ```
  180. ### Dashboard
  181. 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.
  182. ```
  183. PM> Install-Package DotNetCore.CAP.Dashboard
  184. ```
  185. In 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.
  186. ```c#
  187. services.AddCap(x =>
  188. {
  189. //...
  190. // Register Dashboard
  191. x.UseDashboard();
  192. // Register to Consul
  193. x.UseDiscovery(d =>
  194. {
  195. d.DiscoveryServerHostName = "localhost";
  196. d.DiscoveryServerPort = 8500;
  197. d.CurrentNodeHostName = "localhost";
  198. d.CurrentNodePort = 5800;
  199. d.NodeId = 1;
  200. d.NodeName = "CAP No.1 Node";
  201. });
  202. });
  203. ```
  204. The default dashboard address is :[http://localhost:xxx/cap](http://localhost:xxx/cap), you can configure relative path `/cap` with `x.UseDashboard(opt =>{ opt.MatchPath="/mycap"; })`.
  205. ## Contribute
  206. 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.
  207. ### License
  208. [MIT](https://github.com/dotnetcore/CAP/blob/master/LICENSE.txt)