Import External State
React to events in a foreign bounded context in order to trigger a state transition in the current bounded context.
Problem
One part of a business domain - a bounded context, needs to inform another bounded context about internal state changes that have occurred, in order for the latter to trigger its own internal state changes.
Let’s envision two bounded contexts A and B; internal events in A should not be published externally (to B), and it’s not desirable to let A explicitly trigger a state change in B via a command (that decision resides with B).
Solution
Let the foreign context (A in the aforementioned example) publish an external event that is consumed by the current context (B), and translate the external event into an internal event via a command.
Example
In a bike rental domain, there exists two bounded contexts - Inventory and Rental. As new bikes are registered with Inventory, Rental must be informed about their availability to allow them to be rented.
The event model is shown in figure 1:
Figure 1 - Reacting to foreign events via an automation
The RegistrationUpdates
read model is realized as a transformation from an internal event (BikeRegisteredEvent
) in the Inventory context to an external event (called BikeCreatedEvent
in the implementation below); implied in the read model is the use of an event broker to publish the external event.
The Processor
is a background component that consumes BikeCreatedEvent
and translates it into a suitable UpdateAvailabilityCommand
, yielding an internal AvailabilityUpdatedEvent
in the Rental context.
In Listing 1 the internal BikeRegisteredEvent is transformed to the external BikeCreatedEvent for publishing to the Rental context.
@Component
public class BikeEventPublisher {
@Autowired
private EventGateway eventGateway;
@EventHandler
public void on(BikeRegisteredEvent event) {
eventGateway.publish(new BikeCreatedEvent(event.bikeId()));
}
}
Listing 1 - Internal event to external event transformation
Listing 2 demonstrates the translation from the BikeCreatedEvent
to a matching UpdateAvailabilityCommand
.
@Component
public class Processor {
@Autowired
private CommandGateway commandGateway;
@EventHandler
public void on(BikeCreatedEvent event) {
commandGateway.send(new UpdateAvailabilityCommand(event.bikeId()));
}
}
Listing 1 - Translating the external event to trigger an internal state change in Rental
In this example, an EventGateway and a so-called integration context supported by Axon Server is used for context-to-context event publish and subscribe. Other event brokers such as Kafka are of course suitable as well.
|