方法1使用@Async注解
使用spring applicationContext 发布事件
|
applicationContext.publishEvent(new TestEvent()); |
@EventListener和@Async注解
|
@Async @EventListener public void onApplicationEvent(TestEvent event) throws Exception { Thread.sleep(10000L); log.info("event:" + event.getClass().getCanonicalName()); throw new Exception("fuck you"); } |
SpringApplication添加@EnableAsync注解
|
@EnableAsync @SpringBootApplication public class Server { public static void main( String[] args ) { SpringApplication.run(Server.class); } } |
@Configuration注册一个TaskExecutor Bean
|
@Bean(value="taskExecutor") public TaskExecutor getTaskExecutor () { ConcurrentTaskExecutor executor = new ConcurrentTaskExecutor(); return executor; } |
方法2 自定义SimpleApplicationEventMulticaster
|
@Bean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME) public SimpleApplicationEventMulticaster getApplicationEventMulticaster(BeanFactory beanFactory) { log.info("getApplicationEventMulticaster called"); ConcurrentTaskExecutor executor = new ConcurrentTaskExecutor(); SimpleApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster(beanFactory); multicaster.setTaskExecutor(executor); multicaster.setErrorHandler(TaskUtils.getDefaultErrorHandler(true)); return multicaster; } |
Posted in: spring practise
Comments are closed.