One , Synchronous and asynchronous events

Synchronization events : In a thread , Execute business in sequence , Do one thing before you do the next .

Asynchronous events : In a thread , Colleagues who do one thing , You can start a new thread to do another thing , So two things can be done at the same time .

An example is given to explain the usage scenarios of synchronous events and asynchronous events , Sometimes a complete piece of code logic , It may be divided into several parts , Take the most common registration , Suppose the whole process is :

1, Click Register ;

2, Inspection information database ;

3, Send mail ;

4, Return to user .

The code is right , But not the best , The disadvantages are as follows :

① The logic is complex , Business coupling .

② Low efficiency

join 2 and 3 Need separately 1 second , Then the user clicks register 2 The result will be in seconds .

Synchronous events can help us solve the problem ① problem , We handle email independently , Put it in the event , This registration method is only two steps , When finished, issue an event to execute 3, It can solve the problem of business coupling .

Asynchronous events can perfectly solve the above two problems , Registration method execution 2 operation , After execution, an asynchronous event is published , Start another thread to execute 3 operation , The thread where the registration method is located can be returned to the user directly , This not only realizes the business decoupling, but also improves the efficiency , Users click to register ,1 You'll see the response in seconds .

Two ,Spring Event mechanism

Spring Event sending monitoring involves three parts

1,ApplicationEvent

Represents the event itself , Custom events need to inherit this class , It can be used to transfer data , For example, the above email operation

2,ApplicationEventPublishAware

Event Emitter , By implementing this interface , To trigger events

3,ApplicationListener

Event listener interface , The business logic of the event is encapsulated in the listener

Three , Implementation of asynchronous event mechanism simulation registration

There are two ways: configuration file and annotation .

1, Configuration file mode

TestEvent
public class TestEvent extends ApplicationEvent { private TestParam source;
public TestEvent(TestParam source) { super(source); this.source = source; } }
@Data public class TestParam { private String email; }
 TestListener
@Component public class TestListener implements ApplicationListener<TestEvent>
{ @Override public void onApplicationEvent(TestEvent testEvent) { TestParam
param = (TestParam) testEvent.getSource();
System.out.println("....... start .......");
System.out.println(" Send mail :"+param.getEmail());
System.out.println("....... end ....."); } }
TestPublish
@Component public class TestPublish implements ApplicationEventPublisherAware
{ private static ApplicationEventPublisher applicationEventPublisher; @Override
public void setApplicationEventPublisher(ApplicationEventPublisher
applicationEventPublisher) { TestPublish.applicationEventPublisher =
applicationEventPublisher; } public static void publishEvent(ApplicationEvent
communityArticleEvent) {
applicationEventPublisher.publishEvent(communityArticleEvent); } }
spring-context.xml
<bean id="applicationEventAsyncMulticaster"
class="org.springframework.context.event.SimpleApplicationEventMulticaster">
<property name="taskExecutor"> <bean
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="5"/> <property name="keepAliveSeconds"
value="3000"/> <property name="maxPoolSize" value="50"/> <property
name="queueCapacity" value="200"/> </bean> </property> </bean>
  be careful : If you add <propery name="taskExecutor", Then execute asynchronously , Otherwise, it is synchronous .

2, Annotation method

use @Async You need to add some support to the configuration file , Thread pool also needs to be configured
<!-- open @AspectJ AOP agent --> <aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- Task executor --> <task:executor id="executor" pool-size="10"/> <!-- Enable annotation Scheduling Support
@Async --> <task:annotation-driven executor="executor"
proxy-target-class="true"/> TestListener Add to method in @Async @Component public class
TestListener implements ApplicationListener<TestEvent> { @Async @Override
public void onApplicationEvent(TestEvent testEvent) { TestParam param =
(TestParam) testEvent.getSource(); System.out.println("....... start .......");
System.out.println(" Send mail :"+param.getEmail());
System.out.println("....... end ....."); } }

Listener In fact, it can be done more thoroughly , Using annotations @EventListener Alternative implementation ApplicationListener, The idea is to scan the annotation to create a listener and add it to the ApplicationContext in .

TestListenerHandler
@Component public class TestEventHandler { @Async @EventListener public void
handleTestEvent(TestEvent testEvent) { TestParam param = (TestParam)
testEvent.getSource(); System.out.println("....... start .......");
System.out.println(" Send mail :"+param.getEmail());
System.out.println("....... end ....."); } }
Four , summary

use Spring Event mechanism can help us eliminate the coupling relationship between different services , It can also improve the efficiency of implementation , It should be selected flexibly according to business scenarios .

Technology
©2019-2020 Toolsou All rights reserved,
Codeup——601 | problem A: task scheduling Image explanation of over fitting and under fitting CSS architecture design Message quality platform series | Full link troubleshooting How to use it quickly html and css Write static page 2021 year 1 Monthly programmer salary statistics , average 14915 element Codeup——604 | problem B: Full Permutation NOI2019 travels intermediate JAVA Data structure knowledge that programmers should master Random forest R Language implementation