DotNetCore.CAP
public void ConfigureServices(IServiceCollection services) { ...... services.AddDbContext<AppDbContext>(); services.AddCap(x => { //如果你使用的 EF 进行数据操作,你需要添加如下配置: x.UseEntityFramework<AppDbContext>(); //可选项,你不需要再次配置 x.UseSqlServer 了 //如果你使用的ADO.NET,根据数据库选择进行配置: x.UseSqlServer("数据库连接字符串"); x.UseMySql("数据库连接字符串"); x.UsePostgreSql("数据库连接字符串"); //如果你使用的 MongoDB,你可以添加如下配置: x.UseMongoDB("ConnectionStrings"); //注意,仅支持MongoDB 4.0+集群 //CAP支持 RabbitMQ、Kafka、AzureServiceBus 等作为MQ,根据使用选择配置: x.UseRabbitMQ("ConnectionStrings"); x.UseKafka("ConnectionStrings"); x.UseAzureServiceBus("ConnectionStrings"); });
services.AddCap(x => { //... // 注册 Dashboard x.UseDashboard(); // 注册节点到 Consul x.UseDiscovery(d => { d.DiscoveryServerHostName = "localhost"; d.DiscoveryServerPort = 8500; d.CurrentNodeHostName = "localhost"; d.CurrentNodePort = 5800; d.NodeId = 1; d.NodeName = "CAP No.1 Node"; }); });
public class PublishController : Controller { private readonly ICapPublisher _capBus; public PublishController(ICapPublisher capPublisher) { _capBus = capPublisher; } //不使用事务 [Route("~/without/transaction")] public IActionResult WithoutTransaction() { _capBus.Publish("xxx.services.show.time", DateTime.Now); return Ok(); } //Ado.Net 中使用事务,自动提交 [Route("~/adonet/transaction")] public IActionResult AdonetWithTransaction() { using (var connection = new MySqlConnection(ConnectionString)) { using (var transaction = connection.BeginTransaction(_capBus, autoCommit: true)) { //业务代码 _capBus.Publish("xxx.services.show.time", DateTime.Now); } } return Ok(); } //EntityFramework 中使用事务,自动提交 [Route("~/ef/transaction")] public IActionResult EntityFrameworkWithTransaction([FromServices]AppDbContext dbContext) { using (var trans = dbContext.Database.BeginTransaction(_capBus, autoCommit: true)) { //业务代码 _capBus.Publish("xxx.services.show.time", DateTime.Now); } return Ok(); } } 订阅 Action Method 在 Action 上添加 CapSubscribeAttribute 来订阅相关消息。 public class PublishController : Controller { [CapSubscribe("xxx.services.show.time")] public void CheckReceivedMessage(DateTime datetime) { Console.WriteLine(datetime); } } Service Method 如果你的订阅方法没有位于 Controller 中,则你订阅的类需要继承 ICapSubscribe: namespace xxx.Service { public interface ISubscriberService { public void CheckReceivedMessage(DateTime datetime); } public class SubscriberService: ISubscriberService, ICapSubscribe { [CapSubscribe("xxx.services.show.time")] public void CheckReceivedMessage(DateTime datetime) {
public void ConfigureServices(IServiceCollection services) { //注意: 注入的服务需要在 `services.AddCap()` 之前 services.AddTransient<ISubscriberService,SubscriberService>(); services.AddCap(x=>{});
[CapSubscribe("xxx.services.show.time", Group = "group1" )] public void ShowTime1(DateTime datetime) { } [CapSubscribe("xxx.services.show.time", Group = "group2")] public void ShowTime2(DateTime datetime) { }
services.AddCap(x => { x.DefaultGroup = "default-group-name"; });