Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Spring event release monitoring, sequential monitoring and asynchronous monitoring

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is about how to implement Spring event release listening, sequential listening and asynchronous listening. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1. Event notification of Spring

Spring event notification is essentially publish-subscribe, that is, producer-consumer; it embodies the observer design pattern or callback notification, so how are Spring events used?

There are three elements: publisher-- > event-- > listener

2. Spring event notification use

Spring events must rely on the Spring container, so when I write demo, I need Spring-boot-starter.

Events for org.springframework.boot spring-boot-starter 2.1.1.RELEASE org.projectlombok lombok 1.18.4 2.1 Spring

The event of Spring is defined in the ApplicationEvent class, and we can customize the event entity javabean according to our own needs.

@ Datapublic class TestSpringEvent extends ApplicationEvent {/ * * Create a new ApplicationEvent. * * @ param source the object on which the event initially occurred (never {@ code null}) * / public TestSpringEvent (Object source) {super (source);} private Integer code; private String message;}

Track the source code:

Public abstract class ApplicationEvent extends EventObject {/ * * use serialVersionUID from Spring 1.2 for interoperability. * / private static final long serialVersionUID = 7099057708183571937L; / * System time when the event happened. * / private final long timest / * * Create a new ApplicationEvent. * @ param source the object on which the event initially occurred (never {@ code null}) * / public ApplicationEvent (Object source) {super (source); this.timestamp = System.currentTimeMillis ();} / * * Return the system time in milliseconds when the event happened. * / public final long getTimestamp () {return this.timest}}

You can see that ApplicationEvent has an attribute timestamp, that is, the time when the event was generated, and there is an Object source attribute. This source has a specific meaning, and the official doc is The object on which the Event initially occurred. That is, the entity class that publishes the event.

Further tracking

Public class EventObject implements java.io.Serializable {private static final long serialVersionUID = 5516075349620653480L; / * The object on which the Event initially occurred. * / protected transient Object source; / * * Constructs a prototypical Event. * * @ param source The object on which the Event initially occurred. * @ exception IllegalArgumentException if source is null. * / public EventObject (Object source) {if (source = = null) throw new IllegalArgumentException ("null source"); this.source = source;} / * The object on which the Event initially occurred. * * @ return The object on which the Event initially occurred. * / public Object getSource () {return source;} / * * Returns a String representation of this EventObject. * * @ return An a String representation of this EventObject. * / public String toString () {return getClass () .getName () + "[source=" + source + "]";}}

Defines an unserializable object in which an event occurs

2.2 event snooping 2.2.1 interface implementation

The listening for Spring events is defined by ApplicationListener, and we write two to test the order in which the listening is performed.

@ Componentpublic class TestApplicationListener implements ApplicationListener {/ / @ Async public void onApplicationEvent (TestSpringEvent event) {System.out.println ("code is:\ t" + event.getCode () + ",\ tmessage is:\ t" + event.getMessage ()) } @ Componentpublic class TestApplicationListenerCopy implements ApplicationListener {/ / @ Async public void onApplicationEvent (TestSpringEvent event) {System.out.println ("2:code is:\ t" + event.getCode () + ",\ tmessage is:\ t" + event.getMessage ());}}

Tracking the code, you can see that ApplicationListener is a functional interface

@ FunctionalInterfacepublic interface ApplicationListener extends EventListener {/ * * Handle an application event. * @ param event the event to respond to * / void onApplicationEvent (E event);}

Spring event listeners default to single-thread synchronous execution, and asynchronous execution requires the @ Async annotation of Spring, or custom thread pool implementation.

2.2.2 Annotation implementation

You can also use @ EventListener

Package com.feng.spring.listener; import com.feng.spring.event.TestSpringEvent;import org.springframework.context.event.EventListener;import org.springframework.scheduling.annotation.Async;import org.springframework.stereotype.Component; @ Componentpublic class TestApplicationListener2 {/ / @ Async @ EventListener public void onApplicationEvent (TestSpringEvent event) {System.out.println ("step2:code is:\ t" + event.getCode () + ",\ tmessage is:\ t" + event.getMessage ()) } @ Componentpublic class TestApplicationListener2Copy {/ / @ Async @ EventListener public void onApplicationEvent (TestSpringEvent event) {System.out.println ("step3:code is:\ t" + event.getCode () + ",\ tmessage is:\ t" + event.getMessage ());}}

Write two implementations in the same way

2.3 event release

The publishing of Spring events is defined in the ApplicationEventPublisher class, and ApplicationContext inherits this class, so ApplicationContext has the ability to publish events and has been injected into Spring's bean container to obtain it directly.

Public class SpringEventMain {public static void main (String [] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext (); context.scan (SpringEventMain.class.getCanonicalName ()); context.refresh (); TestSpringEvent testSpringEvent = new TestSpringEvent (new SpringEventMain ()); testSpringEvent.setCode (10000); testSpringEvent.setMessage ("- My Spring task event-"); context.publishEvent (testSpringEvent) }}

Note:

New TestSpringEvent (new SpringEventMain ())

The source here is the instance object of the incoming publication event.

After running, print the following log:

/ software/jdk1.8.0_191/bin/java-javaagent:/software/ideaIde/lib/idea_rt.jar=36631:/software/ideaIde/bin-Dfile.encoding=UTF-8-classpath / software/jdk1.8.0_191/jre/lib/charsets.jar:/software/jdk1.8.0_191/jre/lib/deploy.jar:/software/jdk1.8.0_191/jre/lib/ext/cldrdata.jar:/software/jdk1.8.0_191/jre/lib/ext/ Dnsns.jar:/software/jdk1.8.0_191/jre/lib/ext/jaccess.jar:/software/jdk1.8.0_191/jre/lib/ext/jfxrt.jar:/software/jdk1.8.0_191/jre/lib/ext/localedata.jar:/software/jdk1.8.0_191/jre/lib/ext/nashorn.jar:/software/jdk1.8.0_191/jre/lib/ext/sunec.jar:/software/jdk1.8.0_191/ Jre/lib/ext/sunjce_provider.jar:/software/jdk1.8.0_191/jre/lib/ext/sunpkcs11.jar:/software/jdk1.8.0_191/jre/lib/ext/zipfs.jar:/software/jdk1.8.0_191/jre/lib/javaws.jar:/software/jdk1.8.0_191/jre/lib/jce.jar:/software/jdk1.8.0_191/jre/lib/jfr.jar:/software/jdk1.8.0_ 191/jre/lib/jfxswt.jar:/software/jdk1.8.0_191/jre/lib/jsse.jar:/software/jdk1.8.0_191/jre/lib/management-agent.jar:/software/jdk1.8.0_191/jre/lib/plugin.jar:/software/jdk1.8.0_191/jre/lib/resources.jar:/software/jdk1.8.0_191/jre/lib/rt.jar:/home/huahua/IdeaProjects/feng/spring-event/ Target/classes:/home/huahua/.m2/repository/org/springframework/boot/spring-boot-starter/2.1.1.RELEASE/spring-boot-starter-2.1.1.RELEASE.jar:/home/huahua/.m2/repository/org/springframework/boot/spring-boot/2.1.1.RELEASE/spring-boot-2.1.1.RELEASE.jar:/home/huahua/.m2/repository/org/springframework/spring-context/5.1.3.RELEASE/spring- Context-5.1.3.RELEASE.jar:/home/huahua/.m2/repository/org/springframework/spring-aop/5.1.3.RELEASE/spring-aop-5.1.3.RELEASE.jar:/home/huahua/.m2/repository/org/springframework/spring-beans/5.1.3.RELEASE/spring-beans-5.1.3.RELEASE.jar:/home/huahua/.m2/repository/org/springframework/spring-expression/5.1.3.RELEASE/spring- Expression-5.1.3.RELEASE.jar:/home/huahua/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/2.1.1.RELEASE/spring-boot-autoconfigure-2.1.1.RELEASE.jar:/home/huahua/.m2/repository/org/springframework/boot/spring-boot-starter-logging/2.1.1.RELEASE/spring-boot-starter-logging-2.1.1.RELEASE.jar:/home/huahua/.m2/repository/ch/ Qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar:/home/huahua/.m2/repository/ch/qos/logback/logback-core/1.2.3/logback-core-1.2.3.jar:/home/huahua/.m2/repository/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar:/home/huahua/.m2/repository/org/apache/logging/log4j/log4j- To-slf4j/2.11.1/log4j-to-slf4j-2.11.1.jar:/home/huahua/.m2/repository/org/apache/logging/log4j/log4j-api/2.11.1/log4j-api-2.11.1.jar:/home/huahua/.m2/repository/org/slf4j/jul-to-slf4j/1.7.25/jul-to-slf4j-1.7.25.jar:/home/huahua/.m2/repository/javax/annotation/javax. Annotation-api/1.3.2/javax.annotation-api-1.3.2.jar:/home/huahua/.m2/repository/org/springframework/spring-core/5.1.3.RELEASE/spring-core-5.1.3.RELEASE.jar:/home/huahua/.m2/repository/org/springframework/spring-jcl/5.1.3.RELEASE/spring-jcl-5.1.3.RELEASE.jar:/home/huahua/.m2/repository/org/yaml/snakeyaml/ 1.23/snakeyaml-1.23.jar:/home/huahua/.m2/repository/org/projectlombok/lombok/1.18.4/lombok-1.18.4.jar com.feng.spring.SpringEventMain

17DV 54VOV 05.347 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner-Identified candidate component class: file [/ home/huahua/IdeaProjects/feng/spring-event/target/classes/com/feng/spring/listener/TestApplicationListener.class]

17 file 54 file 05.352 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner-Identified candidate component class: [/ home/huahua/IdeaProjects/feng/spring-event/target/classes/com/feng/spring/listener/TestApplicationListener2.class]

17PUR 54VOV 05.353 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner-Identified candidate component class: file [/ home/huahua/IdeaProjects/feng/spring-event/target/classes/com/feng/spring/listener/TestApplicationListener3.class]

17PUR 54VOV 05.353 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner-Identified candidate component class: file [/ home/huahua/IdeaProjects/feng/spring-event/target/classes/com/feng/spring/listener/TestApplicationListenerCopy.class]

17VOUR 54VOR 05.358 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext-Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@64b8f8f4

17VOUR 54VOV 05.380 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'

17VOUR 54VOR 05.438 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'

17VOUR 54VOR 05.440 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'

17VOUR 54VOV 05.443 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'

17VOUR 54VOV 05.444 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'

17VOUR 54VOUR 05.451 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'testApplicationListener'

17VOUR 54VOV 05.466 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'testApplicationListener2'

17VOUR 54VOV 05.470 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'testApplicationListener3'

17VOUR 54VOR 05.471 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'testApplicationListenerCopy'

17 testApplicationListener2': 54 testApplicationListener2': 05.490 [main] DEBUG org.springframework.context.event.EventListenerMethodProcessor-1 @ EventListener methods processed on bean 'testApplicationListener2': {public void com.feng.spring.listener.TestApplicationListener2.onApplicationEvent (com.feng.spring.event.TestSpringEvent) = @ org.springframework.context.event.EventListener (condition=, value= [], classes= [])}

17 EventListener methods processed on bean 54 testApplicationListener3': 05.491 [main] DEBUG org.springframework.context.event.EventListenerMethodProcessor-1 @ EventListener methods processed on bean 'testApplicationListener3': {public void com.feng.spring.listener.TestApplicationListener3.onApplicationEvent (com.feng.spring.event.TestSpringEvent) = @ org.springframework.context.event.EventListener (condition=, value= [], classes= [])}

Step2:code is: 10000, message is:-My Spring task event-

Step3:code is: 10000, message is:-My Spring task event-

Code is: 10000, message is:-My Spring task event-

2:code is: 10000, message is:-My Spring task event-

Process finished with exit code 0

Indicates that the Spring event publication subscription was successful. At the same time, the use of annotated listening is prior to implementing class listening. what if we need to listen in the order of execution? For example, some listeners execute first?

2.4 Spring Sequential listener

The above examples are actually annotations or implementation classes, and listeners are out of order. What if we want to implement sequential monitoring? We need the implementation of the Ordered interface. The implementation provided or exposed by Spring is as follows

If execution order is required, Spring provides SmartApplicationListener and GenericApplicationListener to choose from.

Among them, GenericApplicationListener,Spring officially recommended us to provide adapter implementation.

/ * * Extended variant of the standard {@ link ApplicationListener} interface, * exposing further metadata such as the supported event and source type. * *

As of Spring Framework 4.2, this interface supersedes the Class-based * {@ link SmartApplicationListener} with full handling of generic event types. * * @ author Stephane Nicoll * @ since 4.2 * @ see SmartApplicationListener * @ see GenericApplicationListenerAdapter * / * Extended variant of the standard {@ link ApplicationListener} interface, * exposing further metadata such as the supported event and source type. * *

As of Spring Framework 4.2, this interface supersedes the Class-based * {@ link SmartApplicationListener} with full handling of generic event types. * * @ author Stephane Nicoll * @ since 4.2 * @ see SmartApplicationListener * @ see GenericApplicationListenerAdapter * / public interface GenericApplicationListener extends ApplicationListener, Ordered {/ * Determine whether this listener actually supports the given event type. * @ param eventType the event type (never {@ code null}) * / boolean supportsEventType (ResolvableType eventType); / * * Determine whether this listener actually supports the given source type. *

The default implementation always returns {@ code true}. * @ param sourceType the source type, or {@ code null} if no source * / default boolean supportsSourceType (@ Nullable Class sourceType) {return true;} / * Determine this listener's order in a set of listeners for the same event. *

The default implementation returns {@ link # LOWEST_PRECEDENCE}. * / @ Override default int getOrder () {return LOWEST_PRECEDENCE;}}

In fact, ApplicationListener provides many default implementations in Spring, including SmartApplicationListener, smart listeners.

Let's try it next.

* / public interface SmartApplicationListener extends ApplicationListener, Ordered {/ * * Determine whether this listener actually supports the given event type. * @ param eventType the event type (never {@ code null}) * / / supportsEventType and supportsSourceType true at the same time, the listener will execute the event type boolean supportsEventType (Class sourceType) {return true;} / * Determine this listener's order in a set of listeners for the same event supported by the listener. *

The default implementation returns {@ link # LOWEST_PRECEDENCE}. * / @ Override default int getOrder () {return LOWEST_PRECEDENCE;}}

Three implementation methods. Supported types, supported event classes, execution order

Package com.feng.spring.listener; import com.feng.spring.SpringEventMain;import com.feng.spring.event.TestSpringEvent;import org.springframework.context.ApplicationEvent;import org.springframework.context.event.SmartApplicationListener;import org.springframework.stereotype.Component; @ Componentpublic class OrderedListener implements SmartApplicationListener {public boolean supportsEventType (Class sourceType) {return SpringEventMain.class==sourceType;} public int getOrder () {return 5 } public void onApplicationEvent (ApplicationEvent event) {System.out.println ("my execute step is 55555555555555555555555555555555");} @ Componentpublic class OrderedListenerCopy implements SmartApplicationListener {public boolean supportsEventType (Class sourceType) {return SpringEventMain.class==sourceType;} public int getOrder () {return 6;} public void onApplicationEvent (ApplicationEvent event) {System.out.println ("my execute step is 666666666666666666666666666666");}}

Write 2 in the same way, and the execution results are as follows:

/ software/jdk1.8.0_191/bin/java-agentlib:jdwp=transport=dt_socket,address=127.0.0.1:46603,suspend=y Server=n-javaagent:/software/ideaIde/lib/rt/debugger-agent.jar-Dfile.encoding=UTF-8-classpath / software/jdk1.8.0_191/jre/lib/charsets.jar:/software/jdk1.8.0_191/jre/lib/deploy.jar:/software/jdk1.8.0_191/jre/lib/ext/cldrdata.jar:/software/jdk1.8.0_191/jre/lib/ext/dnsns.jar:/software/jdk1.8.0_191/jre/lib / ext/jaccess.jar:/software/jdk1.8.0_191/jre/lib/ext/jfxrt.jar:/software/jdk1.8.0_191/jre/lib/ext/localedata.jar:/software/jdk1.8.0_191/jre/lib/ext/nashorn.jar:/software/jdk1.8.0_191/jre/lib/ext/sunec.jar:/software/jdk1.8.0_191/jre/lib/ext/sunjce_provider.jar:/software/jdk1.8 . 0_191/jre/lib/ext/sunpkcs11.jar:/software/jdk1.8.0_191/jre/lib/ext/zipfs.jar:/software/jdk1.8.0_191/jre/lib/javaws.jar:/software/jdk1.8.0_191/jre/lib/jce.jar:/software/jdk1.8.0_191/jre/lib/jfr.jar:/software/jdk1.8.0_191/jre/lib/jfxswt.jar:/software/jdk1.8.0 _ 191/jre/lib/jsse.jar:/software/jdk1.8.0_191/jre/lib/management-agent.jar:/software/jdk1.8.0_191/jre/lib/plugin.jar:/software/jdk1.8.0_191/jre/lib/resources.jar:/software/jdk1.8.0_191/jre/lib/rt.jar:/home/huahua/IdeaProjects/feng/spring-event/target/classes:/home/huahua/.m2/repository/org/springframework/ Boot/spring-boot-starter/2.1.1.RELEASE/spring-boot-starter-2.1.1.RELEASE.jar:/home/huahua/.m2/repository/org/springframework/boot/spring-boot/2.1.1.RELEASE/spring-boot-2.1.1.RELEASE.jar:/home/huahua/.m2/repository/org/springframework/spring-context/5.1.3.RELEASE/spring-context-5.1.3.RELEASE.jar:/home/huahua/. M2Universe repositoryamp orgrepositoryhip orgrepositoryChargRgrepositoryChargSpringframeworkChargFramBean 5.1.3.RELEASE .jarrestlage homehuahip .m2repositoryscarp orgframeworkpact springframeworkpin springframeworkChargRembeansRays 5.1.3.RELEASE.jarrestlash homehuahuaand.m2repositoryhand springFramframe workworkspringFuctionExpression5.1.3.RELEASEGAME springFrasionExpression5.1.3.RELEASE.jarbur. M2Universe repositoryUniverse orgUniverse springframeworkxbootingMyotKey autofinancing rebalance 2.1.RELEASE.jarrizhuahuplet.m2andrepositoryandorgspringframeworksprotscarbootscarp2.1.1.RELEASEX springwaystartersofloggingfunds 2.1.1.RELEASE.jarmonger horse startertrick logginglure 2.1.1.RELEASE.jarmonger horse startup chossetqoslogbackand logbacktext classic.1.3 1.2.3.jar:/home/huahua/.m2/repository/ch/qos/logback/logback-core/1.2.3/logback-core-1.2.3.jar:/home/huahua/.m2/repository/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar:/home/huahua/.m2/repository/org/apache/logging/log4j/log4j-to-slf4j/2.11.1/log4j-to-slf4j-2. 11.1.jar:/home/huahua/.m2/repository/org/apache/logging/log4j/log4j-api/2.11.1/log4j-api-2.11.1.jar:/home/huahua/.m2/repository/org/slf4j/jul-to-slf4j/1.7.25/jul-to-slf4j-1.7.25.jar:/home/huahua/.m2/repository/javax/annotation/javax.annotation-api/1.3.2/javax.annotation-api-1. 3.2.jarJREREASE repositoryhip orgrepositoryhip orgreingframeworkash springwaycoreCharger 5.1.3.RELEASE.jarJRREREGRAPHUTHUAUAUR .m2repositoryUniorgspringframeworkSpringJCLUR 5.1.3.RELEASE.jarJarSure homehuahuaplex 5.1.3.RELEASE.jarJarSure homeamlue snakeyamlThue 1.23 snakeyamland 1.23 snakeyamlPROMETER huahuahuahu.m2repositoryrepositoryorgkeyaml M2/repository/org/projectlombok/lombok/1.18.4/lombok-1.18.4.jar:/software/ideaIde/lib/idea_rt.jar com.feng.spring.SpringEventMain

Connected to the target VM, address: '127.0.0.1 virtual 46603, transport:' socket'

18RV 37RV 51.002 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner-Identified candidate component class: file [/ home/huahua/IdeaProjects/feng/spring-event/target/classes/com/feng/spring/listener/OrderedListener.class]

18RV 37RV 51.009 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner-Identified candidate component class: file [/ home/huahua/IdeaProjects/feng/spring-event/target/classes/com/feng/spring/listener/OrderedListenerCopy.class]

18RV 37RU 51.017 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@37d31475

18RV 37RU 51.055 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'

18RV 37RU 51.129 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'

18RV 37RU 51.132 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'

18RV 37RU 51.135 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'

18RV 37RU 51.136 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'

18RV 37RU 51.145 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'orderedListener'

18RV 37RU 51.154 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'orderedListenerCopy'

My execute step is 555555555555555555555555555

My execute step is 6666666666666666666666666666

Disconnected from the target VM, address: '127.0.0.1 virtual 46603, transport:' socket'

Process finished with exit code 0

The sequential monitoring is realized.

2.5 Asynchronous snooping

Spring uses ThreadPoolTaskExecutor to perform asynchronous tasks, which is actually SchedulingTaskExecutor. It uses @ EnableAsync annotation @ Async annotation to call asynchronous listening events.

Let's try it.

Package com.feng.spring.config; import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor;import java.util.concurrent.ThreadFactory;import java.util.concurrent.atomic.AtomicInteger; @ Configurationpublic class AsyncConfig {@ Bean public Executor initExecutor () {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor () / / customize the thread name, you can also customize the thread group executor.setThreadFactory (new ThreadFactory () {private final AtomicInteger threadNumber = new AtomicInteger (1)) @ Override public Thread newThread (Runnable r) {Thread t = newThread (Thread.currentThread () .getThreadGroup (), r, "async-eventListener-" + threadNumber.getAndIncrement (), 0); return t;}}); executor.setCorePoolSize (10) Executor.setMaxPoolSize (20); executor.setKeepAliveSeconds (5); executor.setQueueCapacity (100); / / executor.setRejectedExecutionHandler (null); return executor;}} @ EnableAsync@Componentpublic class TestApplicationListener implements ApplicationListener {@ Async public void onApplicationEvent (TestSpringEvent event) {System.out.println ("code is:\ t" + event.getCode () + ",\ tmessage is:\ t" + event.getMessage ()) / / distinguish System.out.println (Thread.currentThread () .getThreadGroup () + "/" + Thread.currentThread () .getName ()) by thread group/ name;}}

Execution result:

/ software/jdk1.8.0_191/bin/java-agentlib:jdwp=transport=dt_socket,address=127.0.0.1:44287,suspend=y Server=n-javaagent:/software/ideaIde/lib/rt/debugger-agent.jar-Dfile.encoding=UTF-8-classpath / software/jdk1.8.0_191/jre/lib/charsets.jar:/software/jdk1.8.0_191/jre/lib/deploy.jar:/software/jdk1.8.0_191/jre/lib/ext/cldrdata.jar:/software/jdk1.8.0_191/jre/lib/ext/dnsns.jar:/software/jdk1.8.0_191/jre/lib / ext/jaccess.jar:/software/jdk1.8.0_191/jre/lib/ext/jfxrt.jar:/software/jdk1.8.0_191/jre/lib/ext/localedata.jar:/software/jdk1.8.0_191/jre/lib/ext/nashorn.jar:/software/jdk1.8.0_191/jre/lib/ext/sunec.jar:/software/jdk1.8.0_191/jre/lib/ext/sunjce_provider.jar:/software/jdk1.8 . 0_191/jre/lib/ext/sunpkcs11.jar:/software/jdk1.8.0_191/jre/lib/ext/zipfs.jar:/software/jdk1.8.0_191/jre/lib/javaws.jar:/software/jdk1.8.0_191/jre/lib/jce.jar:/software/jdk1.8.0_191/jre/lib/jfr.jar:/software/jdk1.8.0_191/jre/lib/jfxswt.jar:/software/jdk1.8.0 _ 191/jre/lib/jsse.jar:/software/jdk1.8.0_191/jre/lib/management-agent.jar:/software/jdk1.8.0_191/jre/lib/plugin.jar:/software/jdk1.8.0_191/jre/lib/resources.jar:/software/jdk1.8.0_191/jre/lib/rt.jar:/home/huahua/IdeaProjects/feng/spring-event/target/classes:/home/huahua/.m2/repository/org/springframework/ Boot/spring-boot-starter/2.1.1.RELEASE/spring-boot-starter-2.1.1.RELEASE.jar:/home/huahua/.m2/repository/org/springframework/boot/spring-boot/2.1.1.RELEASE/spring-boot-2.1.1.RELEASE.jar:/home/huahua/.m2/repository/org/springframework/spring-context/5.1.3.RELEASE/spring-context-5.1.3.RELEASE.jar:/home/huahua/. M2Universe repositoryamp orgrepositoryhip orgrepositoryChargRgrepositoryChargSpringframeworkChargFramBean 5.1.3.RELEASE .jarrestlage homehuahip .m2repositoryscarp orgframeworkpact springframeworkpin springframeworkChargRembeansRays 5.1.3.RELEASE.jarrestlash homehuahuaand.m2repositoryhand springFramframe workworkspringFuctionExpression5.1.3.RELEASEGAME springFrasionExpression5.1.3.RELEASE.jarbur. M2Universe repositoryUniverse orgUniverse springframeworkxbootingMyotKey autofinancing rebalance 2.1.RELEASE.jarrizhuahuplet.m2andrepositoryandorgspringframeworksprotscarbootscarp2.1.1.RELEASEX springwaystartersofloggingfunds 2.1.1.RELEASE.jarmonger horse startertrick logginglure 2.1.1.RELEASE.jarmonger horse startup chossetqoslogbackand logbacktext classic.1.3 1.2.3.jar:/home/huahua/.m2/repository/ch/qos/logback/logback-core/1.2.3/logback-core-1.2.3.jar:/home/huahua/.m2/repository/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar:/home/huahua/.m2/repository/org/apache/logging/log4j/log4j-to-slf4j/2.11.1/log4j-to-slf4j-2. 11.1.jar:/home/huahua/.m2/repository/org/apache/logging/log4j/log4j-api/2.11.1/log4j-api-2.11.1.jar:/home/huahua/.m2/repository/org/slf4j/jul-to-slf4j/1.7.25/jul-to-slf4j-1.7.25.jar:/home/huahua/.m2/repository/javax/annotation/javax.annotation-api/1.3.2/javax.annotation-api-1. 3.2.jarJREREASE repositoryhip orgrepositoryhip orgreingframeworkash springwaycoreCharger 5.1.3.RELEASE.jarJRREREGRAPHUTHUAUAUR .m2repositoryUniorgspringframeworkSpringJCLUR 5.1.3.RELEASE.jarJarSure homehuahuaplex 5.1.3.RELEASE.jarJarSure homeamlue snakeyamlThue 1.23 snakeyamland 1.23 snakeyamlPROMETER huahuahuahu.m2repositoryrepositoryorgkeyaml M2/repository/org/projectlombok/lombok/1.18.4/lombok-1.18.4.jar:/software/ideaIde/lib/idea_rt.jar com.feng.spring.SpringEventMain

Connected to the target VM, address: '127.0.0.1 transport 44287 socket'

19 Identified candidate component class 08 Identified candidate component class 24.692 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner-file [/ home/huahua/IdeaProjects/feng/spring-event/target/classes/com/feng/spring/config/AsyncConfig.class]

19 Identified candidate component class 08VR 24.730 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner-Identified candidate component class: file [/ home/huahua/IdeaProjects/feng/spring-event/target/classes/com/feng/spring/listener/TestApplicationListener.class]

19Rom 08RV 24.741 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext-Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@37d31475

19Rom 08RV 24.782 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'

19Creating shared instance of singleton bean 08VOV 25.091 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'

19Creating shared instance of singleton bean 08Ride 25.094 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'

19Creating shared instance of singleton bean 08Ride 25.099 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'

19 Creating shared instance of singleton bean 08Rd 25.100 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'

19 Creating shared instance of singleton bean 08 Creating shared instance of singleton bean 25. 106 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAsyncAnnotationProcessor'

19 Creating shared instance of singleton bean 08VOV 25.109 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'org.springframework.scheduling.annotation.ProxyAsyncConfiguration'

19 Creating shared instance of singleton bean 08Ride 25.252 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'asyncConfig'

19 Creating shared instance of singleton bean 08Ride 25.261 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'testApplicationListener'

19 Creating shared instance of singleton bean 08Ride 25.299 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'initExecutor'

19Initializing ExecutorService 08VOV 25.330 [main] INFO org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor-Initializing ExecutorService 'initExecutor'

Code is: 10000, message is:-My Spring task event-

Java.lang.ThreadGroup [name=main,maxpri=10] / async-eventListener-1

Look at the thread name, it has been executed asynchronously

[name=main,maxpri=10] / async-eventListener-13. Summary

The event of Spring notifies demo that it has completed. If you need detailed Spring events from publish to subscription, you need to track the publishEvent process of Spring's ApplicationContext. In fact, very detailed events are also defined during the startup of Spring's ApplicationContext. Use intellij idea analysis, as follows:

The essence of Spring event notification: producer-consumer, embodies the observer pattern of the design pattern.

Thank you for reading! On "how to achieve Spring event release monitoring, sequential monitoring and asynchronous monitoring" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, you can share it out for more people to see it!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report