Spring event mechanism asynchronous operation

1 The benefits of the spring event mechanism: decoupling, for one-to-many operations, you can contact code coupling

 

2 For the operations to be decoupled, many of them can be operated asynchronously, and the response time of the main thread will be faster. The event mechanism provided by spring is synchronous by default.

 

	@Override
	public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
		ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
		for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
			Executor executor = getTaskExecutor();
                        //Thread pool exists, take asynchronous operation
			if (executor != null) {
				executor.execute(new Runnable() {
					@Override
					public void run() {
						invokeListener(listener, event);
					}
				});
			}
			else {
				invokeListener(listener, event);
			}
		}
	}

 If you want to achieve asynchronous operation, you need to provide the implementation of ApplicationEventMulticaster in the publisher, and inject a thread pool, so that asynchronous operation can be achieved;

Disadvantage: all operations are asynchronous

 

3 Another implementation of asynchrony: @Async can use this annotation on the event publishing method to make the entire process of event publishing and subscriber processing asynchronous. It is best to use asynchronous annotations to customize a thread pool and define more than thread pools Repulsion mechanism after capacity to prevent thread loss

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326129567&siteId=291194637