I am trying to implement a simple event publishing...
# questions
c
I am trying to implement a simple event publishing solution but fear I am barking up the wrong tree. I am using version 6.2.3. Basically I want to send emails when certain events take place (password change or reset) and thought publishing an event to a listener that subsequently sends the email would make sense. However the code I currently have is based on the Spring "ApplicationEventPublisher" and a listener on the Spring "@EventListener". In addition to this my listener is based under ./src/main/groovy as a Spring Component. Needless to say this is not working. The publish code runs but the Listener is either not running or at least not listening for an event. I saw the following docs - https://async.grails.org/latest/guide/index.html#notifying Does anyone have a simple example/pointers how to get this working? Basically I want to have a service that will Publish an Event after-which a generic Email Service can listen and act on this and take care of sending. The user wont notice any delay etc Much appreciated if someone can help me out
j
event publishing is a reasonable approach to this. I'd use the built-in spring publishing since it can already support async publishing. We wrapper our event publisher in a service to match the grails conventions, something like this:
Copy code
class EventService implements ApplicationEventPublisherAware {
    private ApplicationEventPublisher publisher
     
    void publish(MyEventClass applicationEvent) {
        if (publisher) {
            publisher.publishEvent(applicationEvent)
        }
    }

    @Override
    void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher
    }
}
As for subscribing to events, you add a method on a bean and annotate it with either
@EventListener
or
@TransactionalEventListener
. You'll want to use TransactionEventListener with
@Async
to asynchronously trigger a response.
Copy code
@Async
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, condition = '#event.myEnum == T(com.example.MyEnum).CREATE')
void myResponseMethod(MyEventClass event)
Note that the syntax for the event listener uses spring el
Some more information is here: https://www.baeldung.com/spring-events
Spring Events will be on the same node only though. You'll have to use something like Spring Integration to work across a cluster.
c
👍