Build domain events

We build domain events based on Spring's ApplicationEvent. This allows us to publish and listen to domain events easily. Here is how the DomainEvent class looks:

...
public abstract class DomainEvent extends ApplicationEvent {
public DomainEvent(Object source) {
super(source);
}
public long occurredAt() {
// Return the underlying implementation's timestamp
return getTimestamp();
}
}

As you can see, it extends from ApplicationEvent and provides its own API, the occurredAt() method, so that we don't rely too much on ApplicationEvent to get the time the event occurred.

The following is how the DomainEventPublisher interface looks:

public interface DomainEventPublisher {
void publish(DomainEvent event);
}

As you can see, it has only one API, the publish() method. Its Spring-based implementation looks like the following:

@Component
public class DefaultDomainEventPublisher implements DomainEventPublisher {
@Autowired
private ApplicationEventPublisher actualPublisher;

@Override
public void publish(DomainEvent event) {
actualPublisher.publishEvent(event);
}
}

As you can see, we inject the actual publisher, the ApplicationEventPublisher instance here, and then delegate the publishing to it. With this implementation, we can publish and listen to domain events inside the same JVM. In the future, we can create implementations based on AMQP or the Redis Pub/Sub, to provide distributed domain event processing. For now, this Spring-based implementation is good enough.

DomainEvent, DomainEventPublisher, and DefaultDomainEventPublisher all live in the com.taskagile.domain.common.event package. They can be shared between multiple models.

Even though inside the User module we don't need to handle UserRegisteredEvent, let's create a handler to see how to receive this domain event.

The following is the UserRegisteredEventHandler inside the com.taskagile.domain.model.user package:

...
@Component
public class UserRegisteredEventHandler {
...
@EventListener(UserRegisteredEvent.class)
public void handleEvent(UserRegisteredEvent event) {
log.debug("Handling `{}` registration event",
event.getUser().getEmailAddress());
// This is only a demonstration of the domain event listener
}
}

As you can see, an event handler is a standard component that has a method annotated with the @EventListener annotation, which is only interested in UserRegisteredEvent. The method body itself simply writes debug information into the log. In order to see this log, you will need to add the following logging level in src/main/resources/application.properties:

logging.level.com.taskagile=DEBUG

With this setting, all of the debug information of the application itself will show up in the output.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.93.175