当前位置:网站首页>Domain events and integration events are not so big
Domain events and integration events are not so big
2022-07-28 09:46:00 【biyusr】
Preface
As the system architecture evolves , Many nouns have sprung up , Such as : Microservices 、 Grayscale Publishing 、 Resource isolation 、 Containers 、 field / Integration events, etc , Listen, it's really tall , Let many little friends have a feeling that they can't conquer ; In fact, many things may have been used before , It's just a different name , Don't panic even if it's not applied , Now many wheels are very mature , It's easy to use . Let's talk about the common domain events and integration events .
Text
1. summary
Microservices and DDD The prevailing Era , Domain events and integration events are often mentioned ; For events , Small partners can understand according to different scenes , For example, when you click a button , This is an event ( Click event ), Or when purchasing goods, payment is successful , It can also be understood as an event , Just as we define everything in life .
1.1 Field events
Field events (Domain Event) It is triggered by an action in a specific field , It's an event that occurs in the past ( Behavior can be manipulated by people , It can also be automatic ) ;
In fact, in the project , Usually we use domain events in an application process , For example, in user management , When the user registration is successful , Need to send email or SMS reminder ; User management can be simply understood as a field , Successful user registration is an event , Sending reminders is the way to deal with Events .
The metaphor of domain may not be particularly appropriate here , If your partner wants to know more , You can see DDD( Domain-driven design ) Related information .
For my personal understanding , I think the main purpose of domain events is to make code easier to maintain , Make business easier to expand , That is to optimize the business level of the code . Here's the picture :
![]()
For the original way , I believe many of my friends have written such code logic as I have done before , Don't think about the code order , Just roll the code directly , But the scalability is not good , For example, what if I want to add a wechat to send , We have to add... On the original basis , If you don't send text messages in two days , You have to change the original code . Is this against the of software development Opening and closing principle , Try not to change the original logic code , Avoid repeated modifications 、 Repeat the test .
For the optimized way , Just publish an event after the registration is successful , As for what kind of message to send later, don't worry , As long as the event message is captured , Just add additional extended processor classes , Even cancel , Just don't capture the corresponding event , There is no need to change the logic of the original user registration code . Events in this way can be understood as domain events .
Little buddy, think back , Have you done this before when optimizing your code , It was just not called a domain event at that time .
1.2 Integration events
Integration events (IntegrationEvent) It also refers to events arising from past actions ( Behavior can be manipulated by people , It can also be automatic ), It is generally used to span multiple microservices or external systems .
For example, the current e-commerce system , The order module and logistics module will be split into different micro services , Usually after the order is paid successfully , The logistics module needs to know the details related to the order , Only in this way can we track the logistics according to the order . So after the order is paid successfully , An event will be released , After the logistics system subscribes to the event, it can process the corresponding business logic .
I think the main purpose of integration events is to reduce the docking coupling between service modules or systems , As long as the event type is agreed , There will be little connection between the event sending module and the event processing module , Easy to extend and maintain . Pictured :

The original way , For example, my older friends should have used it before , Of course, there are many traditional enterprise projects in this way . In this way, the docking between modules or systems is mainly carried out in the form of interface , In this way, the docking cost is slightly higher , Because the order service also needs to develop the logic to call the logistics service interface , And all kinds of joint commissioning , Consider interface timeout 、 Failure and other situations ; In addition, what if the systems of other business modules need to be connected , If the interface specifications are different , We have to develop a set of call logic again and again , In this way, the later order service module becomes very bloated , And the coupling between modules is relatively high .
The optimized method is relatively good , After successful payment of the order , Just post the event , The rest need not interfere too much , After the corresponding business module subscribes to the message, it can carry out relevant business processing ; This mode will be very convenient even if other business modules are added , The coupling between modules is relatively low . Because messages between modules need to be transmitted , So we need EventBus To do this . This way looks good , but Third party message middleware is needed for message forwarding and storage , Such as RabbitMq、Kafka etc. ; In addition, during use , Message persistence 、 All cases of message loss need to be considered , A separate series of articles will be published in the follow-up, saying that this .
2. demonstration
For technology landing , The great gods have made the wheel , Let's just use it .
2.1 Field events
Technical introduction
MediatR Yes, it is .Net Simple mediator pattern implemented , No other dependencies are needed to handle in-process messaging , Support request / Respond to 、 command 、 Inquire about 、 Synchronous or asynchronous delivery of notifications and events , adopt C# Generic intelligent scheduling .
I won't go into details here , For details, you can see this article I shared before 《 Study with me .NetCore And MediatR There seems to be an ignition 》
Case practice
Prepare one API project , Introduce the corresponding Nuget package , And register for related services , as follows :

Simulate user registration and successfully publish domain events , Here, add an interface to the default controller for testing , The code is as follows :

The published event information is actually an object information , It's just that this class follows MediatR It is agreed to inherit the corresponding interface , as follows :

Add event processing logic , That is, how to handle after capturing the event , The code is as follows :

This processing class can be added as needed , Add an email and SMS here , If you need other ways , You only need to inherit the corresponding interface according to the contract , And implement the corresponding method to process the business logic .
It works :

Is it easy to use Easy~~~, The same is true for integration events .
2.2 Integration events
Technical introduction
This one is commonly used by myself CAP and Masstransit, About CAP I also shared an article 《 Distributed transactions are ultimately consistent -CAP The frame is easy to handle 》, It can also be used to publish Events , No more details here .
Masstransit It's a free 、 Open source .NET Distributed application framework , Lightweight message bus (EventBus) , Specifically used to transmit and receive messages ; Integrate many message oriented middleware , Such as :RabbitMQ、AcitveMQ、Azure Service Bus、Kafka、Redis etc. , Here we mainly talk about application , For more details, please check the official website , as follows :
Official website address :http://masstransit-project.com/getting-started/
Open source address :https://github.com/MassTransit/MassTransit
Case practice
In fact, it can be demonstrated in the way of memory , But to better match the real scene , Here the RabbitMQ The way to demonstrate , So first you need to install RabbitMQ, For convenience , Or use it Docker Installation by , If the Docker I don't know you , Check out the series of articles I share 《Docker series 》.
Make sure there are Docker Under the environment of , Execute the following command :
docker run -di --name myrabbit -e RABBITMQ_DEFAULT_USER=admin -e RABBITMQ_DEFAULT_PASS=admin -p 15672:15672 -p 5672:5672 -p 25672:25672 -p 61613:61613 -p 1883:1883 rabbitmq:managementThis command specifies that the default user is admin, The default password is also admin, If you can log in normally RabbitMQ System , Represents that the installation was successful , as follows :

notes : I use Alibaba cloud server here , Therefore, you need to open the port in the security group and firewall 15672 and 5672 The interview of ,15672 yes RabbitMQ Of Web Interface ,5672 It is needed for communication between programs .
Prepare two API project , A simulated order release event , A simulated logistics subscription event , First of all, we need to introduce relevant Nuget package :MassTransit、MassTransit.RabbitMQ, And register for related services , as follows :

Simulate the successful payment event of order publishing , Add the corresponding interface in the default controller for demonstration , as follows :

The definition of events here is directly defined as a public class library for convenience , It is also a simple class , The contents are as follows :

Logistics module
Simulate the successful payment completion event of logistics subscription , A little attention needs to be paid here , Because relevant business processing is required after subscribing to events , So when registering for the service , You need to register the corresponding processor , The logic of processing class is as follows :

Register the processor as well , as follows :

When starting, the port of the order is 5001, The port of the logistics module is 5000, As long as the ports of the two modules are not the same , Ports cannot be reused , So you can run and see the effect , Both modules start up :
Access the publishing interface in the order module , After receiving the event message, the logistics module will handle it as follows :

notes : The above demonstration method does not specify the corresponding queue , So the use of RabbitMQ Medium Fanout Pattern ,Fanout It is a publish and subscribe mode of broadcast mechanism , That is, all subscribers can receive the events published by the producer , In the actual scene, this mode is not used much , Usually the more commonly used is direct Pattern , Small partners can be designated according to the actual situation ; About RabbitMQ I'm sorting out a series of articles , The follow-up meeting will be shared with you .
Related source address :https://gitee.com/CodeZoe/dot-net-core-study-demo
summary
Let's talk so much about the introduction and use of domain events and integration events for the time being , Just a brief introduction to my understanding and application of domain events and integration events , More details need to be configured and improved by small partners according to actual business needs , But the usage is so simple ; For message loss 、 Persistence and other related issues , The following articles will be shared with the message queue .

边栏推荐
- Inside database system distributed system
- FPGA development learning open source website summary
- The maximum recommended number of rows for MySQL is 2000W. Is it reliable?
- 力扣376-摆动序列——贪心
- Use xposed to crack the software
- Window source code analysis (I): things with decorview
- C# 窗体应用使用对象绑定 DataGridView 数据绑定
- Feign call exception [running, pool size = 10, active threads = 10, queued tasks = 0, completed tasks = n]
- Express builds a simple local background (1)
- HashSet内部原理解析
猜你喜欢

21天学习挑战赛-《Autosar从入门到精通-实战篇》

MATLAB的实时编辑器

【日志】日志干什么的?日志工厂是什么?log4j 的配置和使用? log4j.properties 文件配置、log4j jar包坐标

咸鱼ESP32实例—MQTT 点亮LED

What is cross domain? How to solve the cross domain problem?

Network engineering -- ranking of Chinese universities in Soft Science

JDBC连接数据库

Leetcode - hashtable topic

NTU Lin Xuantian's "machine learning cornerstone" problem solving and code implementation | [you deserve it]

Salted fish esp32 instance - mqtt lit LED
随机推荐
Translation recommendation | debugging bookkeeper protocol - unbounded ledger
How promise instance solves hell callback
SQL Server、MySQL主从搭建,EF Core读写分离代码实现
How does gbase 8A use preprocessing to quickly insert data?
Promise实例如何解决地狱回调
Opencv4.60 installation and configuration
[JVM] JVM refers to floating point number
关于CLR GC调优的一些问题
Changes in the relationship between data and application in IT industry
3分钟带你了解微信小程序开发
树上启发式合并
2.9.5 ext JS object type processing and convenient methods
Analysis of the internal principle of ArrayList
WPF布局之控件随着窗口等比放大缩小,适应多分辨率满屏填充应用
Method parameter transfer mechanism of C #
C signed and unsigned byte variables
Machine learning (10) -- hypothesis testing and regression analysis
Introduction to SD card (based on spec3.0)
什么是跨域?如何解决请跨域问题?
Business visualization - make your flowchart'run'(4. Actual business scenario test)






