CQRS implementation with Axon[edit]
According to the diagram above, creating commands, passing them to command bus and then creating events and placing them on event bus is not CQRS yet.php
We have to remember about changing the state of write repository and reading current state from the read database. This is the crucial point of the CQRS pattern.java
Configuring this flow should be easy as well. While passing the command to the command gateway, Spring searches methods annotated with @CommandHandler with command type as argument.web
class SubmitApplicationCommand { |
public class ApplicationService { |
private final CommandGateway commandGateway; |
public CompletableFuture<Void> createForm(String appId) { |
return CompletableFuture.supplyAsync(() -> new SubmitExpertsFormCommand(appId, "Android")) |
.thenCompose(commandGateway::send); |
Command handler is responsible, among other things, for sending the created event to the event bus.app
It places an event object to statically imported apply() method from AggregateLifecycle. The event is later dispatched to find expected handlers and thanks to configured event store, all events are saved in DB automatically.ide
class ApplicationSubmittedEvent { |
public class ApplicationAggregate { |
public ApplicationAggregate(SubmitApplicationCommand command) { |
this.id = command.getAppId; |
apply(new ApplicationSubmittedEvent(command.getAppId(), command.getCategory())); |
To change the state of the write DB, we need to provide a method annotated with @EventHandler.ui
The application can contain multiple event handlers. Each of them should perform one specific task like sending emails, logging or saving in database.this
public class ProjectingEventHandler { |
private final IApplicationSubmittedProjection projection; |
public CompletableFuture<Void> onApplicationSubmitted(ExpertsFormSubmittedEvent event) { |
return projection.submitApplication(event.getApplicationId(), event.getCategory()); |
If we want to determine the processing order of all event handlers,spa
we can annotate a class with @Order and set a sequence number. submitApplication() method is responsible for making all the necessary changes and saving new data in write DB.code
These are all vital points to make our app event sourced with CQRS pattern principles. Of course, these principles can be applied only in some parts of our application depending on business needs.orm
Event sourcing is not suitable for every application or module we are building. It is also worth to be cautious while implementing this pattern because a more complex application can be hard to maintain.
Conclusion[edit]
Implementation of CQRS and Event Sourcing is straightforward with Axon framework. More details about advanced configuration can be found on Axon’s website https://docs.axonframework.org/.