Home > Java > javaTutorial > body text

Introduction to springboot event monitoring (with code)

不言
Release: 2019-04-12 10:36:06
forward
3659 people have browsed it

This article brings you an introduction to springboot event monitoring (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Define events

@Getter
public class TestEvent extends ApplicationEvent {
   private String msg;

   public TestEvent(Object source, String msg) {
       super(source);
       this.msg = msg;
   }
}
Copy after login

Define event monitoring (annotation method)

 @Component
 public class TestListen {
   @EventListener
   public void testListen(TestEvent event) {
       System.out.println(event.getMsg());
   }
}
Copy after login

Note: @Component annotation

Publish event

@Autowired
private ApplicationContext publiser;

@GetMapping("test-listen")
public void testListen() {
    for (int i = 0; i < 10; i++) {
        System.out.println("i = " + i);
    }
    publiser.publishEvent(new TestEvent(this, "测试事件监听"));
    for (int j = 0; j < 10; j++) {
       System.out.println("j = " + j);
   }
}
Copy after login

Execution sequence during testing:

  1. i loop
  2. Print "event = [test event listening]"
  3. j loop

Asynchronous monitoring

Listening plus @Async annotation

@Component
public class TestListen {
   @EventListener
   @Async
   public void testListen(TestEvent event) {
       for (int i = 0; i < 10; i++) {
           System.out.println("event = [" + event.getMsg() + "]");
       }
   }
}
Copy after login

Execution order during testing:

  1. i loop
  2. j loop
  3. Print "event = [test event listening]"

The above is the detailed content of Introduction to springboot event monitoring (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template