-
Notifications
You must be signed in to change notification settings - Fork 0
Async and Filtering Events π¦
Table Of Contents
By default, Spring events are synchronous, meaning that the publisher thread blocks until all listeners interested in a particular event have finished processing the event.
What if we have a listener that takes too long to get executed an publishing synchronously ?
The solution is to make the event listener running in Async mode. To do so, we have to annotate the listener with @Async annotation ( @EnableAsync is required on top of the Spring configuration).
Please note that, the usage of @Async comes with its limitations :
- Cannot publish event by returning value.
- Use ApplicationEventPublisher.publish() if any.
- Exceptions are not propagated to the caller.
- Use AsyncUncaughExceptionHandler interface if any.
An external call is really slow and it doesn't make sense to block the whole use case. Executing this call as an event asynchronously is the best approach.
import lombok.RequiredArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class AnalyticsCustomerRegisteredListener {
private final AnalyticsService analyticsService;
@EventListener
@Async
public void onRegisterEvent(CustomerRegisteredEvent event) {
analyticsService.registerNewCustomer(event.getCustomer());
}
}
Β© 2024 | Lyes Sefiane
All Rights Reserved | CC BY-NC-ND 4.0