NetCore结合CAP事件总线实现分布式事务——入门(1)
CAP
一、入门
-
CAP 是一个EventBus,同时也是一个在微服务或者SOA系统中解决分布式事务问题的一个框架。它有助于创建可扩展,可靠并且易于更改的微服务系统。
-
在微软的 eShopOnContainer 微服务示例项目中,推荐使用 CAP 作为生产环境可用的 EventBus。
事件总线是一种机制,它允许不同的组件彼此通信而不彼此了解。 组件可以将事件发送到Eventbus,而无需知道是谁来接听或有多少其他人来接听。 组件也可以侦听Eventbus上的事件,而无需知道谁发送了事件。 这样,组件可以相互通信而无需相互依赖。 同样,很容易替换一个组件。 只要新组件了解正在发送和接收的事件,其他组件就永远不会知道.
相对于其他的 Service Bus 或者 Event Bus, CAP 拥有自己的特色,它不要求使用者发送消息或者处理消息的时候实现或者继承任何接口,拥有非常高的灵活性。我们一直坚信约定大于配置,所以CAP使用起来非常简单,对于新手非常友好,并且拥有轻量级。
二、环境搭建
- 安装nuget
Install-Package DotNetCore.CAP
- 安装RabbitMq
官网下载
(转载)RabbitMq详解
三、配置信息
Publisher
1. Startup.cs
ConfigureServices方法
services.AddCap(x =>
{
// 如果你的 SqlServer 使用的 EF 进行数据操作,你需要添加如下配置:
// 注意: 你不需要再次配置 x.UseSqlServer(""")
x.UseEntityFramework<PubDBContext>();
//配置RabbitMq信息
x.UseRabbitMQ(rb =>
{
//RabbitMq所在服务器地址
rb.HostName = "localhost";
//设置得用户名(默认生成得是guest用户,密码也是guest,
//这里是我在Mq里添加得admin用户,密码设置的admin)
rb.UserName = "admin";
//设置得密码
rb.Password = "admin";
//默认端口
rb.Port = 5672;
//一个虚拟主机里面可以有若干个Exchange和Queue,同一个虚拟主机里面不能有相同名称的Exchange或Queue。
//将一个主机虚拟为多个,类似路由
rb.VirtualHost = "Angel2022";
//使用得交换机名称
rb.ExchangeName = "AngelCapExchange";
//设置消息得过期时间
rb.QueueMessageExpires = 24 * 3600 * 10;
});
}
//添加 PubDBContext efCoreApp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, PubDBContext efCoreApp)
{
efCoreApp.Database.EnsureCreated();
}
2.PubDbContext
appsettings.json文件配置连接字符串
using Microsoft.EntityFrameworkCore;
namespace _01_Publisher
{
public class PubDBContext : DbContext
{
public PubDBContext()
{
}
public PubDBContext(DbContextOptions<PubDBContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
}
}
3.PubController
using DotNetCore.CAP;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
namespace _01_Publisher.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class PubController : ControllerBase
{
private ICapPublisher _capBus;
private PubDBContext _pubDBContext;
public PubController(ICapPublisher capBus, PubDBContext pubDBContext)
{
this._capBus = capBus;
this._pubDBContext = pubDBContext;
}
[HttpGet]
public IActionResult SendMsg()
{
//引入的CAP,发布订阅,Publish(订阅的路由键(RoutingKey),发布的数据(Query))
//路由键的设置,接收订阅的一方,通过路由键来接收对于的订阅
_capBus.Publish("angel", contentObj: new Person { Id = 1, Name = "11" });
return Content("发送成功");
}
}
}
Subscriber
1.Startup.cs
<PackageReference Include="DotNetCore.CAP.Dashboard" Version="3.1.2" />
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
//注入数据库
services.AddDbContext<SubDBContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:AngelDBContext"]));
//注册cap事件
services.AddCap(x =>
{
x.UseEntityFramework<SubDBContext>();
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天)
});
//这里是引入可视化面板
x.UseDashboard();//使用Cap可视化面板
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SubDBContext efCoreApp)
{
efCoreApp.Database.EnsureCreated();//数据库不存在自动创建
}
2.SubDBContext
using Microsoft.EntityFrameworkCore;
namespace _02_Subscriber
{
public class SubDBContext : DbContext
{
public SubDBContext()
{
}
public SubDBContext(DbContextOptions<SubDBContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
}
}
3.SubController
namespace _02_Subscriber.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class SubController : ControllerBase
{
private ILogger _log;
public SubController(ILogger<SubController> log)
{
this._log = log;
}
[NonAction]
//通过标记找寻,路由键为angel的消息
[CapSubscribe("angel")]
public void ReceiveMsg(Person str)
{
if(str!=null)
{
Console.WriteLine($"接收{str.Id}");
_log.LogInformation($"我是订阅者,收到的内容为:{str.Id},{str.Name}");
}
}
}
}
四、运行项目
- 请求发布消息的API
- 查看Cap面板
http://localhost:(运行的端口)/cap
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了