Use separate databases for command and query micro-services with Axon framework and Spring Boot

106 Views Asked by At

I'm trying to implement CQRS and event sourcing patterns with Axon framework and Spring Boot. I created two services with two separate databases (for simplicity, I used two PostgreSQL databases on different ports). I have CustomerEntity and want to implement two simple APIs: creating and listing customers. The thing that I want to do is perfectly described in the following figure (consider that we have customerEntity instead of account):

cqrs and eventsoucing flow

So, I have @CommandHandler and @EventSourcingHandler and @Aggregate in command micro-service and @EventHandler in query micro-service. The problem is when I send a command and apply the CreateCustomerEvent, the event handler does not receive the event, and the customer doesn't persist in the query database.

Here is the code on the command side:

@CommandHandler
public CustomerAggregate(CreateCustomerCommand createCustomerCommand) {
    CustomerMapper mapper = Mappers.getMapper(CustomerMapper.class);
    CustomerCreatedEvent createdEvent = mapper.createCommandToCreateCommand(createCustomerCommand);

    CustomerCreatedEvent customerCreatedEvent = mapper.mapCommandToEvent(createCustomerCommand);

    AggregateLifecycle.apply(customerCreatedEvent);
}

@EventSourcingHandler
public void on(CustomerCreatedEvent event) {
    this.firstname = event.getFirstname();
    this.customerId = event.getCustomerId();
    this.lastname = event.getLastname();
    this.fullName = event.getFullName();
    this.displayName = event.getDisplayName();
    this.accountNumber = event.getAccountNumber();
    this.dateOfBirth = event.getDateOfBirth();
    this.mobileNo = event.getMobileNo();
    this.email = event.getEmail();
    this.customerImage = event.getCustomerImage();
    this.OfficeCode = event.getOfficeCode();
    this.customerStatus = event.getCustomerStatus();
}

And the query side:

@EventHandler
public void on(CustomerCreatedEvent event) {
    CustomerEntity entity = new CustomerEntity();
    BeanUtils.copyProperties(event, entity);
    customerRepository.save(entity);
}

The Axon framework dependency in build.gradle:

implementation('org.axon-framework:axon-spring-boot-starter:4.8.2') {
    exclude group: 'org.axon-framework', module: 'axon-server-connector'
}

Do you know how to solve this, or can you point me to concrete examples?

0

There are 0 best solutions below