[Spring] Event Pub/Sub 기능 예제

ITWeb/개발일반 2021. 3. 3. 11:23

Spring 을 이용해서 간단한 Pub/Sub 기능을 구현 할 수 있는 예제 입니다.

 

관련 Class & Annotation)

ApplicationEventPublisher

@EventListener

 

Pub & Sub 을 위한 Topic Payload)

CustomEventTopicPayload

 

Subscriber Class)

CustomEventSubscriber

 

Code Example)

HelloController : Publisher

@Controller
public class HelloController {

  @Autowired
  ApplicationEventPublisher eventPublisher;

  @GetMapping ("/poc/hello")
  public String hello() {

    eventPublisher.publishEvent(new CustomEventTopicPayload(this, 100));

    return "poc/hello";
  }
}

 

CustomEventSubscriber - Subscriber

@Component
@Log4j2
public class CustomEventSubscriber {

  @EventListener
  public void onEventListener(CustomEventTopicPayload topic) {
    log.debug("{} Topic payload: " + topic.getData(), Thread.currentThread().toString());
  }
}

 

CustomEventTopicPayload - Topic Payload

@Getter
@Setter
public class CustomEventTopicPayload {
  private Object source;
  private int data;

  public CustomEventTopicPayload(Object source) {
    this(source, 0);
  }

  public CustomEventTopicPayload(Object source, int data) {
    this.source = source;
    this.data = data;
  }
}

 

아래 간략한 코드 스니핑은 스프링 4.2 이전 방식 입니다.

public class CustomEventTopicPayload extends ApplicationEvent {}

public class CustomEventSubscriber implements ApplicationListener<CustomEventTopicPayload>{}

 

: