CAP 是一个EventBus,同时也是一个在微服务或者SOA系统中解决分布式事务问题的一个框架【官网】
使用- 第一步:创建发布者(Angel.Cap.Publisher)与订阅者(Angel.Cap.Subscriber)两个应用程序,在Nuget上引用主要依赖:DotNetCore.CAP、DotNetCore.CAP.RabbitMQ;用的是Sql Server,还要引用后面三个引用
- 第二步:搭建发布者 Angel.Cap.Publisher
- 添加数据库连接字符串
"ConnectionStrings": { //连接字符串
"AngelDBContext": "data source=.;initial catalog=AngelCapDB;User ID=sa;Password=sa;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
}
- 添加DBContext
public class PubDBContext : DbContext
{
public PubDBContext()
{
}
public PubDBContext(DbContextOptions options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
}
- Configure和ConfigureServices使用
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
//注入数据库
services.AddDbContext(options => options.UseSqlServer(Configuration["ConnectionStrings:AngelDBContext"]));
//注册cap事件
services.AddCap(x =>
{
x.UseEntityFramework();
x.UseRabbitMQ(rb =>
{
rb.HostName = "localhost";
rb.UserName = "admin";
rb.Password = "admin";
rb.Port = 5672;
rb.VirtualHost = "Angel2022";
rb.ExchangeName = "AngelCapExchange";
rb.QueueMessageExpires = 24 * 3600 * 10;
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, PubDBContext efCoreApp)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
efCoreApp.Database.EnsureCreated();//数据库不存在自动创建
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
- 创建发布接口
[Route("api/[controller]/[action]")]
[ApiController]
public class PubController : ControllerBase
{
private ICapPublisher _capBus;
public PubController(ICapPublisher capBus)
{
this._capBus = capBus;
}
[HttpGet]
public IActionResult SendMsg()
{
for (var i = 0; i < 1000; i++)
{
DateTime date = DateTime.Now;
_capBus.Publish("angel", $"******发布者,发布的内容为: {date},i:{i}*****");
}
return Content("发送成功");
}
}
第三步:搭建订阅者Angel.Cap.Subscriber
- 添加数据库连接字符串,与发布者一样
- 添加DBContext
public class SubDBContext : DbContext
{
public SubDBContext()
{
}
public SubDBContext(DbContextOptions options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
}
- Configure和ConfigureServices使用
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
//注入数据库
services.AddDbContext(options => options.UseSqlServer(Configuration["ConnectionStrings:AngelDBContext"]));
//注册cap事件
services.AddCap(x =>
{
x.UseEntityFramework();
x.UseRabbitMQ(rb =>
{
rb.HostName = "localhost";
rb.UserName = "admin";
rb.Password = "admin";
rb.Port = 5672;
rb.VirtualHost = "Angel2022";
rb.ExchangeName = "AngelCapExchange";
rb.QueueMessageExpires = 24 * 3600 * 10; //队列中消息自动删除时间(默认10天)
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SubDBContext efCoreApp)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
efCoreApp.Database.EnsureCreated();//数据库不存在自动创建
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
- 创建订阅者接口
[Route("api/[controller]/[action]")]
[ApiController]
public class SubController : ControllerBase
{
private ILogger _log;
public SubController(ILogger log)
{
this._log = log;
}
///
/// 订阅者的方法
///
///
[NonAction]
[CapSubscribe("angel")]
public void ReceiveMsg(string str)
{
_log.LogInformation($"我是订阅者,收到的内容为:{str}");
}
}
Cap 面板
在Angel.Cap.Subscriber上使用面板
- 在ConfigureServices的AddCap上调用UseDashboard()
//注册cap事件
services.AddCap(x =>
{
x.UseEntityFramework();
x.UseRabbitMQ(rb =>
{
rb.HostName = "localhost";
rb.UserName = "admin";
rb.Password = "admin";
rb.Port = 5672;
rb.VirtualHost = "Angel2022";
rb.ExchangeName = "Angel_RabbMQ_Exchange";
rb.QueueMessageExpires = 24 * 3600 * 10;
});
x.UseDashboard();//使用Cap可视化面板
});
- 浏览器打开,域名后面加上cap
https://localhost:44368/cap



