Skip to content

Conversation

@lkim0402
Copy link
Collaborator

@lkim0402 lkim0402 commented Nov 6, 2025

기본 구현사항

웹소켓 구현하기

  • 웹소켓 환경 구성
    • spring-boot-starter-websocket 의존성을 추가하세요.
    • 웹소켓 메시지 브로커 설정
      • 메모리 기반 SimpleBroker를 사용하세요.
        • SimpleBroker의 Destination Prefix는 /sub 으로 설정하세요.
          • 클라이언트에서 메시지를 구독할 때 사용합니다.
        • Application Destination Prefix는 /pub 으로 설정하세요.
          • 클라이언트에서 메시지를 발행할 때 사용합니다.
        • STOMP 엔드포인트는 /ws로 설정하고, SockJS 연결을 지원해야 합니다.
  • 메시지 송신
    • 첨부파일이 없는 단순 텍스트 메시지인 경우 STOMP를 통해 메시지를 전송할 수 있도록 컨트롤러를 구현하세요.
      • 클라이언트는 웹소켓으로 /pub/messages 엔드포인트에 메시지를 전송할 수 있어야 합니다.
        • @MessageMapping을 활용하세요.
      • 메시지 전송 요청의 페이로드 타입은 MessageCreateRequest 를 그대로 활용합니다.
    • 첨부파일이 포함된 메시지는 기존의 API (POST /api/messages)를 그대로 활용합니다.
  • 메시지 수신
    • 클라이언트는 채널 입장 시 웹소켓으로 /sub/channels.{channelId}.messages 를 구독해 메시지를 수신합니다.
    • 이를 고려해 메시지가 생성되면 해당 엔드포인트로 메시지를 보내는 컴포넌트를 구현하세요.
      • MessageCreatedEvent를 통해 새로운 메시지 생성 이벤트를 확인하세요.
      • SimpMessagingTemplate를 통해 적절한 엔드포인트로 메시지를 전송하세요.

SSE 구현하기

  • SSE 환경을 구성하세요.
    • 클라이언트에서 SSE 연결을 위한 엔드포인트를 구현하세요.
      • GET /api/sse
    • 사용자별 SseEmitter 객체를 생성하고 메시지를 전송하는 컴포넌트를 구현하세요.
      • connect: SseEmitter 객체를 생성합니다.
      • send, broadcast: SseEmitter 객체를 통해 이벤트를 전송합니다.
      • cleanUp: 주기적으로 ping을 보내서 만료된 SseEmitter 객체를 삭제합니다.
      • ping: 최초 연결 또는 만료 여부를 확인하기 위한 용도로 더미 이벤트를 보냅니다.
    • SseEmitter 객체를 메모리에서 저장하는 컴포넌트를 구현하세요.
      • ConcurrentMap: 스레드 세이프한 자료구조를 사용합니다.
      • List: 사용자 당 N개의 연결을 허용할 수 있도록 합니다. (예: 다중 탭)
    • 이벤트 유실 복원을 위해 SSE 메시지를 저장하는 컴포넌트를 구현하세요.
      • 각 메시지 별로 고유한 ID를 부여합니다.
      • 클라이언트에서 LastEventId를 전송해 이벤트 유실 복원이 가능하도록 해야 합니다.
  • 기존에 클라이언트에서 폴링 방식으로 주기적으로 요청하던 데이터를 SSE를 이용해 서버에서 실시간으로 전달하는 방식으로 리팩토링하세요.
    • 새로운 알림 이벤트 전송
      • 새 알림이 생성되었을 때 클라이언트에 이벤트를 전송하세요.
      • 클라이언트는 이 이벤트를 수신하면 알림 목록에 알림을 추가합니다.
    • 파일 업로드 상태 변경 이벤트 전송
      • 파일 업로드 상태가 변경될 때 이벤트를 발송하세요.
      • 클라이언트는 해당 상태를 수신하면 파일 상태 UI를 다시 렌더링합니다.
    • 채널 갱신 이벤트 전송
      • 채널 정보가 변경될 때, 이벤트를 발송하세요.
      • 클라이언트는 해당 이벤트를 수신하면 채널 UI를 다시 렌더링합니다.
    • 사용자 갱신 이벤트 전송
      • 사용자 정보 또는 로그인 상태가 변경될 때, 이벤트를 발송하세요.
      • 클라이언트는 해당 이벤트를 수신하면 사용자 UI를 다시 렌더링합니다.

배포 아키텍처 구성하기

  • 다음의 다이어그램에 부합하는 배포 아키텍처를 Docker Compose를 통해 구현하세요.
    • Reverse Proxy
      • Nginx 기반의 리버스 프록시 컨테이너를 구성하세요.
      • 역할 및 설정은 다음과 같습니다:
        • /api/, /ws/ 요청은 Backend 컨테이너로 프록시 처리합니다.
        • 이 외의 모든 요청은 정적 리소스(프론트엔드 빌드 결과)를 서빙합니다.
          • 프론트엔드 정적 리소스는 Nginx 컨테이너 내부의 적절한 경로(/usr/share/nginx/html 등)에 복사하세요.
        • 외부에서 접근 가능한 유일한 컨테이너이며, 3000번 포트를 통해 접근할 수 있어야 합니다.
    • Backend
      • Spring Boot 기반의 백엔드 서버를 Docker 컨테이너로 구성하세요.
      • Reverse Proxy를 통해 /api/, /ws/ 요청이 이 서버로 전달됩니다.
    • DB, Memory DB, Message Broker
      • Backend 컨테이너가 접근 가능한 다음의 인프라 컨테이너들을 구성하세요
        • DB: PostgreSQL
        • Memory DB: Redis
        • Message Broker: Kafka
      • 각 컨테이너는 Docker Compose 네트워크를 통해 백엔드에서 통신할 수 있어야 합니다.
      • 외부 네트워크와 단절되어야 합니다.

심화

웹소켓 인증/인가 처리하기

  • 인증 처리
    • 디스코드잇 클라이언트는 CONNECT 프레임의 헤더에 다음과 같이 Authorization 토큰을 포함합니다.
    • 서버 측에서는 ChannelInterceptor를 구현하여 연결 시 토큰을 검증하고, 인증된 사용자 정보를 SecurityContext에 설정해야 합니다.
    • CONNECT 프레임일 때 엑세스 토큰을 검증하는 JwtAuthenticationChannelInterceptor 구현체를 정의하세요.
      • 검증 로직은 이전에 구현한 JwtAuthenticationFilter를 참고하세요.
      • 인증이 완료되면 SecurityContext에 인증정보를 저장하는 대신 accessor 객체에 저장하세요.
    • SecurityContextChannelInterceptor를 등록하여 이후 메시지 처리 흐름에서도 인증 정보를 활용할 수 있도록 구성하세요.
  • 인가 처리
    • AuthorizationChannelInterceptor를 사용해 메시지 권한 검사를 수행합니다.
    • AuthorizationChannelInterceptor를 활용하기 위해의존성을 추가하세요.
    • MessageMatcherDelegatingAuthorizationManager를 활용해 인가 정책을 정의하고, 채널에 추가하세요.

분산 환경 배포 아키텍처 구성하기

  • 다음의 다이어그램에 부합하는 배포 아키텍처를 Docker Compose를 통해 구현하세요.
    • Backend-*
      • deploy.replicas 설정을 활용하세요.
    • Reverse Proxy
      • upstream 블록을 수정해 다음의 로드밸런싱 전략을 적용해 Backend로 트래픽을 분산시켜보세요.
        • Round Robin 기본값
        • Least Connections
        • IP Hash
        • Weight
      • $upstream_addr 변수를 활용해 실제 요청을 처리하는 서버의 IP를 헤더에 추가하고 브라우저 개발자 도구를 활용해 비교해보세요.
  • 분산환경에 따른 InMemoryJwtRegistry의 한계점을 식별하고 Redis를 활용해 리팩토링하세요.
    • 어떤 한계가 있는지 식별하고 PR에 남겨주세요.
    • RedisJwtRegistry 구현체를 활용하세요.
  • 분산환경에 따른 웹소켓과 SSE의 한계점을 식별하고 Kafka를 활용해 리팩토링하세요.
    • 어떤 한계가 있는지 식별하고 PR에 남겨주세요.
    • 일반적인 카프카 이벤트와 다르게 각 서버 인스턴스마다 이벤트를 받을 수 있어야 합니다. 따라서 컨슈머 group id를 적절히 설정하세요.

질문 답변

  1. 분산환경에 따른 InMemoryJwtRegistry의 한계점을 식별하고 Redis를 활용해 리팩토링하세요. 어떤 한계가 있는지 식별하고 PR에 남겨주세요.
  • docker stack deploy를 사용하면서 앱은 3개의 복제본(replica)으로 실행되는 분산 환경이 되었습니다. 기존 InMemoryJwtRegistry는 각 서버의 메모리 안에만 토큰을 저장했고, 이 방식으로는 1번 서버에서 로그인한 사용자가 2번 서버로 요청을 보내면 2번 서버는 그 토큰을 전혀 알지 못해서 오류가 발생합니다.
  • RedisJwtRegistry는 Redis라는 중앙 저장소에 토큰 정보를 저장하고 1, 2, 3번 서버 모두가 동일한 데이터를 공유할 수 있게 됩니다. 그래서 어떤 서버로 요청이 가도 인증이 올바르게 처리됩니다.

lkim0402 added 30 commits June 24, 2025 12:15
- repository  구현체를 application.yml 설정값을 통해 제어
- File*Repository 구현체의 파일을 저장할 디렉토리 경로를 application.yml 설정값을 통해 제어
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker // STOMP 사용 활성화
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

STOMP 사용 활성화 처리

Comment on lines +12 to +22
@Controller
@RequiredArgsConstructor
public class MessageWebSocketController {

private final MessageService messageService;

@MessageMapping("/messages")
public void sendMessage(MessageCreateRequest message) {
messageService.create(message, java.util.Collections.emptyList());
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

웹소켓을 활용한 메세지 송신

Comment on lines +14 to +25
//public class WebSocketRequiredEventListener {
//
// private final SimpMessagingTemplate messagingTemplate;
//
// // 메세지 커밋 이후
// @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
// public void handleMessage(MessageCreatedEvent event) {
// MessageDto messageDto = event.getData();
// UUID channelId = messageDto.channelId();
//
// messagingTemplate.convertAndSend("/sub/channels." + channelId + ".messages", messageDto);
// }
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

메세지 수신

@Repository
public class SseMessageRepository {

private final ConcurrentLinkedDeque<UUID> eventIdQueue = new ConcurrentLinkedDeque<>();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이벤트 순서 보장을 위한 Queue 사용

public class SseMessageRepository {

private final ConcurrentLinkedDeque<UUID> eventIdQueue = new ConcurrentLinkedDeque<>();
private final Map<UUID, SseMessage> messages = new ConcurrentHashMap<>();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

동시성 보장

Comment on lines +37 to +49
// SseEmitter 객체를 생성
public SseEmitter connect(UUID receiverId, UUID lastEventId) {
SseEmitter emitter = createEmitter(receiverId);
if (lastEventId != null) {
senderPool.execute(() ->
restoreEvents(emitter, receiverId, lastEventId)
);
}

ping(emitter, receiverId, "connect", lastEventId);

return emitter;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

객체 전달

Copy link
Collaborator

@joonfluence joonfluence Nov 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

docker-compose 설정 완료 (nginx 제외)

Comment on lines +87 to +91
// Time-based cleanup - run every hour
@Scheduled(fixedRate = 3600000) // 1 hour
public void cleanupOldMessages() {
Instant cutoff = Instant.now().minusSeconds(MAX_AGE_HOURS * 3600);
int removed = 0;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

주기적으로 응답 없는 연결 제외

Comment on lines +18 to +29
@RequiredArgsConstructor
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

private final JwtAuthenticationChannelInterceptor jwtAuthenticationChannelInterceptor;

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// 서버가 클라이언트로 메시지를 보낼 때 사용하는 prefix (subscribe)
config.enableSimpleBroker("/sub");
// 클라이언트가 서버로 메시지를 보낼 때 사용하는 prefix (publish)
config.setApplicationDestinationPrefixes("/pub");
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WebSocketMessageBrokerConfigurer 통해 HTTP 요청 간 JWT 인증 수행

- "8081:8080"
deploy:
mode: replicated
replicas: 3 # 복제
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3대의 분산 환경 구축

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants