当前位置:网站首页>NETCORE combined with cap event bus to realize distributed transaction -- Introduction (1)
NETCORE combined with cap event bus to realize distributed transaction -- Introduction (1)
2022-06-12 14:46:00 【There are poems and distant places】
CAP
One 、 introduction
CAP It's a EventBus, At the same time, it is also a micro service or SOA A framework for solving distributed transaction problems in system . It helps create extensible , A reliable and easy to change microservice system .
In Microsoft eShopOnContainer In the microservice example project , Recommended CAP Available as a production environment EventBus.
The event bus is a mechanism , It allows different components to communicate with each other without understanding each other . Components can send events to Eventbus, You don't need to know who answers or how many others answer . Components can also listen Eventbus Events on the , Without knowing who sent the event . such , Components can communicate with each other without interdependency . Again , It's easy to replace a component . As long as the new component knows what events are being sent and received , Other components will never know .
Compared with other Service Bus perhaps Event Bus, CAP Have their own characteristics , It does not require the user to implement or inherit any interface when sending or processing messages , It has very high flexibility . We have always believed that convention is more important than configuration , therefore CAP It's very simple to use , Very friendly for beginners , And it has lightweight .
Two 、 Environment building
- install nuget
Install-Package DotNetCore.CAP
- install RabbitMq
Download from the official website
( Reprint )RabbitMq Detailed explanation
3、 ... and 、 Configuration information
Publisher
1. Startup.cs
ConfigureServices Method
services.AddCap(x =>
{
// If your SqlServer The use of EF Data manipulation , You need to add the following configuration :
// Be careful : You don't have to configure it again x.UseSqlServer(""")
x.UseEntityFramework<PubDBContext>();
// To configure RabbitMq Information
x.UseRabbitMQ(rb =>
{
//RabbitMq Address of the server
rb.HostName = "localhost";
// Set the user name ( The default generation is guest user , The password is guest,
// This is where I am Mq Added in admin user , Password setting admin)
rb.UserName = "admin";
// Set the password
rb.Password = "admin";
// Default port
rb.Port = 5672;
// A virtual host can have several Exchange and Queue, The same virtual host cannot have the same name Exchange or Queue.
// Virtualize a host into multiple , Similar to routing
rb.VirtualHost = "Angel2022";
// Switch name used
rb.ExchangeName = "AngelCapExchange";
// Set the message expiration time
rb.QueueMessageExpires = 24 * 3600 * 10;
});
}
// add to PubDBContext efCoreApp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, PubDBContext efCoreApp)
{
efCoreApp.Database.EnsureCreated();
}
2.PubDbContext
appsettings.json File configuration connection string
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()
{
// Introduced CAP, Publish subscribe ,Publish( Subscribed routing keys (RoutingKey), Published data (Query))
// Routing key settings , The party receiving the subscription , Receive subscriptions to via routing keys
_capBus.Publish("angel", contentObj: new Person {
Id = 1, Name = "11" });
return Content(" Send successfully ");
}
}
}
Subscriber
1.Startup.cs
<PackageReference Include="DotNetCore.CAP.Dashboard" Version="3.1.2" />
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// Injected database
services.AddDbContext<SubDBContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:AngelDBContext"]));
// register cap event
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; // Automatic deletion time of messages in the queue ( Default 10 God )
});
// Here is the introduction of the visualization panel
x.UseDashboard();// Use Cap Visualization panel
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SubDBContext efCoreApp)
{
efCoreApp.Database.EnsureCreated();// The database does not exist and is automatically created
}

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]
// Find by marking , The routing key is angel The news of
[CapSubscribe("angel")]
public void ReceiveMsg(Person str)
{
if(str!=null)
{
Console.WriteLine($" receive {
str.Id}");
_log.LogInformation($" I'm a subscriber , The content received is :{
str.Id},{
str.Name}");
}
}
}
}
Four 、 Run the project
- Requesting a message API
- see Cap panel
http://localhost:( Running port )/cap
```
边栏推荐
- C secret script Chapter 1: data storage (in-depth analysis) supplement
- 指针相关概念
- 你敢信?開發一個管理系統我只用了兩天
- 【SimpleDateFormat】1. Conversion of date type and text type 2 Thread unsafe
- [wechat applet] 6.1 applet configuration file
- C scanf函数
- Energy chain smart electronics landed on NASDAQ: Bain is the shareholder to become the first share of charging services in China
- Appnium (II) installation and basic use of mitmproxy
- Installation and use of mat
- Module yaml error: Unexpected key in data: static_context [line 9 col 3]
猜你喜欢

C main函数

你敢信?开发一个管理系统我只用了两天

Data collection
![[wechat applet] 1 Introduction to wechat applet](/img/7c/6e62269438a0dd7e7172cb37af9fb9.jpg)
[wechat applet] 1 Introduction to wechat applet

Huawei equipment is configured with H virtual private network

PMP agile knowledge points
![[wechat applet] 4 Introduction to wechat developer tools](/img/9d/0d6c5cc675fb70dde98b25649bd8d8.jpg)
[wechat applet] 4 Introduction to wechat developer tools
![[OCR] aspriseocr C # English, number recognition (not Chinese)](/img/80/198145df663d2eeec6b8b1d7bc47b6.png)
[OCR] aspriseocr C # English, number recognition (not Chinese)

G++ error in compiling Win32 program: undefined reference to '__ imp_ GetStockObject‘

Huawei equipment configuration BGP as number replacement
随机推荐
[Writeup]BUU SQL COURSE1[入门级]
PMP敏捷知识点
JMeter (V) pressure test of Excel file upload interface
JS (III) convert ES6 syntax to Es5 syntax
Software package for optimization scientific research field
C secret arts script Chapter 5 (paragraph) (Section 3)
模块八
【Calendar】1. For globalization 2 But only date can be formatted by SDF 3 Month to -1 4 Week from Sunday is the first day
C常量,不能改变
Module VIII
webdriver入门
QT link error: undefined reference to VTable for "XXX“
Tu oses le croire? Il m'a fallu deux jours pour développer un système de gestion.
Module yaml error: Unexpected key in data: static_context [line 9 col 3]
C secret script Chapter 1: data storage (in-depth analysis) supplement
ADB command (I) record
Unit test (I) unit test with JUnit
Configuring OSPF pseudo connection for Huawei devices
【SimpleDateFormat】1. Conversion of date type and text type 2 Thread unsafe
Easygui query the company name in the document