Class ThreadLocalDomainEventPublisher
java.lang.Object
com.reallifedeveloper.common.domain.event.ThreadLocalDomainEventPublisher
- All Implemented Interfaces:
DomainEventPublisher
A publisher of domain events that keeps track of subscribers on a per-thread basis. It is assumed that subscription and publishing are
done by the same thread, and publishing is handled synchronously. To handle events asynchronously, a subscriber could send a message to a
message queue, or store the event for later processing.
If threads are reused, it is important to call the reset()
method to clear any previous subscribers.
The normal use-case for this class is as follows:
- A request comes in to an application service.
- The application service creates or retrieves an instance of this class and calls the
reset()
method. - The application service registers all necessary subscribers using the
subscribe(DomainEventSubscriber)
method. - The application service delegates to domain services or aggregates, which publish events when something interesting happens in the
domain, using the
publish(DomainEvent)
method.
- Author:
- RealLifeDeveloper
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoid
publish
(DomainEvent event) Publishes a domain event, i.e., calls theDomainEventSubscriber.handleEvent(DomainEvent)
method for each registered subscriber.void
reset()
Removes all subscribers.void
subscribe
(DomainEventSubscriber<? extends DomainEvent> subscriber) Registers an event handler with this publisher.
-
Constructor Details
-
ThreadLocalDomainEventPublisher
public ThreadLocalDomainEventPublisher()
-
-
Method Details
-
subscribe
Registers an event handler with this publisher.- Specified by:
subscribe
in interfaceDomainEventPublisher
- Parameters:
subscriber
- the event handler to register- Throws:
IllegalStateException
- if called while publishing events
-
publish
Publishes a domain event, i.e., calls theDomainEventSubscriber.handleEvent(DomainEvent)
method for each registered subscriber.- Specified by:
publish
in interfaceDomainEventPublisher
- Parameters:
event
- the domain event to publish- Throws:
IllegalStateException
- if called while already publishing events
-
reset
public void reset()Removes all subscribers. Since subscribers are stored on a per-thread basis, and since threads may be reused, this method should be called when starting to handle a new request.- Throws:
IllegalStateException
- if called while publishing events
-