Spring Framework Events

2019-04-06 03:38发布

I was reading through Spring Framework documentation and found a section on raising events in Spring using ApplicationContext. After reading a few paragraphs I found that Spring events are raised synchronously. Is there any way to raise asynchronous events? your help is much appreciated. I am looking something similar which would help me to complete my module.

4条回答
Summer. ? 凉城
2楼-- · 2019-04-06 03:49

Alternative notification strategies can be achieved by implementing ApplicationEventMulticaster (see Javadoc) and its underlying (helper) class hierarchy. Typically you use either a JMS based notification mechanism (as David already suggested) or attach to Spring's TaskExecuter abstraction (see Javadoc).

查看更多
Viruses.
3楼-- · 2019-04-06 03:51

Simplest asynchronous ApplicationListener:

Publisher:

@Autowired
private SimpleApplicationEventMulticaster simpleApplicationEventMulticaster;

@Autowired
private AsyncTaskExecutor asyncTaskExecutor;

// ...

simpleApplicationEventMulticaster.setTaskExecutor(asyncTaskExecutor);

// ...

ApplicationEvent event = new ApplicationEvent("");
simpleApplicationEventMulticaster.multicastEvent(event);

Listener:

@Component
static class MyListener implements ApplicationListener<ApplicationEvent> 
    public void onApplicationEvent(ApplicationEvent event) {
         // do stuff, typically check event subclass (instanceof) to know which action to perform
    }
}

You should subclass ApplicationEvent with your specific events. You can configure SimpleApplicationEventMulticaster and its taskExecutor in an XML file.

You might want to implement ApplicationEventPublisherAware in your listener class and pass a source object (instead of empty string) in the event constructor.

查看更多
Juvenile、少年°
4楼-- · 2019-04-06 03:53

Try this override the ApplicationEventMulticaster bean in resources.groovy so that it uses a thread pool:

Some thing like this worked for me, i.e. I used

import java.util.concurrent.*
import org.springframework.context.event.*

beans = {
    applicationEventMulticaster(SimpleApplicationEventMulticaster) {
        taskExecutor = Executors.newCachedThreadPool()
    }
}
查看更多
女痞
5楼-- · 2019-04-06 03:54

Spring itself (AFAIK) work synchronously, but what you can do is to create your own ApplicationListener proxy - a class that implements this interface but instead of handling the event it just delegates it by sending to another (or new) thread, sending JMS message, etc.

查看更多
登录 后发表回答