[CowAPI] 24. Server Sent Event (Springboot + React)

준돌·2022년 7월 6일
0

오늘의 Cow

목록 보기
29/45

1. 문제

  • 현재 Springboot + React로 Server Sent Event를 구현했습니다.
  • 하지만, 실시간 처리를 하기위해 너무 많은 요청을 보내는 문제가 발생했습니다.

2. 원인

  • 특정 시간을 기준으로 그 시간이 지날때마다 요청을 보내고 있습니다.

3. 해결방법

  • 특정 Event가 발생할때만 실시간으로 요청을 보내려고 합니다.
  • 동기화 방법을 사용해볼까 고려해 보고 있습니다.

4. 코드

  • 아래는 SSE의 코드 입니다.
  • 참고하세용
// 1. Controller [Springboot]

@RestController
public class DashboardController {
    @GetMapping("/dashboard")
    public Flux<ServerSentEvent<DashboardResponseDto>> dashboard() {
        return dashboardService.publish();
    }
}
// 2. Service [Springboot]

@Service
@RequiredArgsConstructor
public class DashboardService {
    private static final Long refreshTime = 2L;
    
    public Flux<ServerSentEvent<DashboardResponseDto>> publish() {
    
    	... // 필요한 로직들 수행 (비동기)
        
        return Flux.interval(Duration.ofSeconds(refreshTime))
                    .map(sequence -> ServerSentEvent.<DashboardResponseDto>builder()
                            .id("/dashboard")
                            .event("event")
                            .data(dashboardResponseDto)
                            .retry(Duration.ofSeconds(refreshTime))
                            .build());
	}
}
// 3. Front [React]

const subscribe = new EventSource(`${url}/dashboard`, {withCredentials: true});

subscribe.addEventListener("event", async (event) => {
  const parsedData = JSON.parse(event.data);

  ... // 필요 로직 수행
}
profile
눈 내리는 겨울이 좋아!

0개의 댓글