>  기사  >  Java  >  springboot 이벤트 모니터링 소개(코드 포함)

springboot 이벤트 모니터링 소개(코드 포함)

不言
不言앞으로
2019-04-12 10:36:063630검색

이 기사는 springboot 이벤트 모니터링(코드 포함)에 대한 소개를 제공합니다. 도움이 필요한 친구들이 참고할 수 있기를 바랍니다.

이벤트 정의

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

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

이벤트 모니터링 정의(주석 방법)

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

참고: @Component Annotation

Publish events

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

테스트 중 실행 순서:

  1. i 루프
  2. 인쇄" 이벤트 = [테스트 이벤트 수신]"
  3. j loop

비동기 청취

listening plus @Async 주석

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

테스트 중 실행 순서:

  1. i loop
  2. j loop
  3. Print "event = [ 테스트 이벤트 청취]"

위 내용은 springboot 이벤트 모니터링 소개(코드 포함)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제