当前位置:网站首页>NetCore结合CAP事件总线实现分布式事务——入门(1)
NetCore结合CAP事件总线实现分布式事务——入门(1)
2022-06-12 14:18:00 【有诗亦有远方】
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
```
边栏推荐
- Wait function in SystemC
- Basic usage of scanner
- C secret script Chapter 1: data storage (in-depth analysis) supplement
- Copy word content to excel and automatically divide it into multiple columns
- Player actual combat 22 to solve the problems of flower screen and Caton
- Remote code injection
- ADB control installation simulator
- 华为设备配置OSPF伪连接
- 使用make方法创建slice切片的坑
- Player actual combat 13 create qtopengl project to promote window control and reload qoopenglwedge
猜你喜欢
对某热水软件的加密参数逆向
Perfect ending | detailed explanation of the implementation principle of go Distributed Link Tracking
Why do Chinese programmers change jobs?
Reverse the encryption parameters of a hot water software
ADB command (2) use monkey to test
【OCR】AspriseOCR C# 英文、數字識別(中文不行)
Llvm pass-- virtual function protection
chapter19 Allocation
Shell脚本到底是什么高大上的技术吗?
Reverse order of Excel
随机推荐
For cross-border e-commerce, the bidding strategy focusing more on revenue - Google SEM
Player actual combat 16 xdecode class
Nesting of C language annotations
Player practice 18 xresample
QT link error: undefined reference to VTable for "XXX“
Ppt cannot be opened, always prompt how to fix it
Leetcode 2176. 统计数组中相等且可以被整除的数对
ADB command (2) use monkey to test
chapter19 Allocation
Leetcode 2185. Counts the string containing the given prefix
QT database realizes page turning function
Player actual combat 12 QT playing audio
Lua tvalue structure
Dynamic search advertising intelligent search for matching keywords
WinDbg preview debug analysis createtoolhelp32snapshot
G++ error in compiling Win32 program: undefined reference to '__ imp_ GetStockObject‘
JS (I) error [err\u module\u not\u found]: cannot find package 'UUID' imported
JS (III) convert ES6 syntax to Es5 syntax
华为设备配置OSPF伪连接
MobileOne: 移动端仅需1ms的高性能骨干,你值得拥有!