Home  >  Article  >  Java  >  Introduction to springboot event monitoring (with code)

Introduction to springboot event monitoring (with code)

不言
不言forward
2019-04-12 10:36:063658browse

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;
   }
}

Define event monitoring (annotation method)

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

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);
   }
}

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() + "]");
       }
   }
}

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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete