Edition 0 Updated to asp. Net core 0


Publishing events through the event bus



Yüklə 11,82 Mb.
Pdf görüntüsü
səhifə130/288
tarix12.07.2023
ölçüsü11,82 Mb.
#136458
1   ...   126   127   128   129   130   131   132   133   ...   288
Publishing events through the event bus 
Finally, the message sender (origin microservice) publishes the integration events with code similar to 
the following example. (This approach is a simplified example that does not take atomicity into 
account.) You would implement similar code whenever an event must be propagated across multiple 
microservices, usually right after committing data or transactions from the origin microservice. 
First, the event bus implementation object (based on RabbitMQ or based on a service bus) would be 
injected at the controller constructor, as in the following code: 
[
Route
(
"api/v1/[controller]"
)] 
public
class
CatalogController : ControllerBase 

private
readonly
CatalogContext _context; 
private
readonly
IOptionsSnapshot _settings; 
private
readonly
IEventBus _eventBus; 
public
CatalogController
(CatalogContext context, 
IOptionsSnapshot settings, 
IEventBus eventBus) 

_context = context; 
_settings = settings; 
_eventBus = eventBus; 

// ...

Then you use it from 
your controller’s methods, like in the UpdateProduct method:
[
Route
(
"items"
)] 
[HttpPost] 
public
async Task 
UpdateProduct
([FromBody]CatalogItem product) 

var
item = await _context.
CatalogItems
.
SingleOrDefaultAsync

i => i.
Id
== product.
Id
); 
// ...
if
(item.
Price
!= product.
Price


var
oldPrice = item.
Price

item.
Price
= product.
Price

_context.
CatalogItems
.
Update
(item); 
var @event = 
new
ProductPriceChangedIntegrationEvent
(item.
Id

item.
Price

oldPrice); 
// Commit changes in original transaction
await _context.
SaveChangesAsync
(); 
// Publish integration event to the event bus


143 
CHAPTER 5 | Designing and Developing Multi-Container and Microservice-Based .NET Applications 
// (RabbitMQ or a service bus underneath)
_eventBus.
Publish
(@event); 
// ...

// ...

In this case, since the origin microservice is a simple CRUD microservice, that code is placed right into 
a Web API controller. 
In more advanced microservices, like when using CQRS approaches, it can be implemented in the 
CommandHandler
class, within the 
Handle()
method. 

Yüklə 11,82 Mb.

Dostları ilə paylaş:
1   ...   126   127   128   129   130   131   132   133   ...   288




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin