Skip to content

Conversation

@lkim0402
Copy link
Collaborator

기본 요구사항

Spring Event - 파일 업로드 로직 분리하기

  • BinaryContentStorage.put을 직접 호출하는 대신 BinaryContentCreatedEvent를 발행하세요.
    • BinaryContentCreatedEvent를 정의하세요.
      • BinaryContent 메타 정보가 DB에 잘 저장되었다는 사실을 의미하는 이벤트입니다.
    • 다음의 메소드에서 BinaryContentStorage를 호출하는 대신 BinaryContentCreatedEvent를 발행하세요.
      • UserService.create/update
      • MessageService.create
      • BinaryContentService.create
    • ApplicationEventPublisher를 활용하세요.
  • 이벤트를 받아 실제 바이너리 데이터를 저장하는 리스너를 구현하세요.
    • 이벤트를 발행한 메인 서비스의 트랜잭션이 커밋되었을 때 리스너가 실행되도록 설정하세요.
    • BinaryContentStorage를 통해 바이너리 데이터를 저장하세요.
  • 바이너리 데이터 저장 성공 여부를 알 수 있도록 메타 데이터를 리팩토링하세요.
    • BinaryContent에 바이너리 데이터 업로드 상태 속성(status)을 추가하세요.
    • BinaryContent의 상태를 업데이트하는 메소드를 정의하세요.
      • 트랜잭션 전파 범위에 유의하세요.
  • 바이너리 데이터 저장 성공 여부를 메타 데이터에 반영하세요.
    • 성공 시 BinaryContent의 status를 SUCCESS로 업데이트하세요.
    • 실패 시 BinaryContent의 status를 FAIL로 업데이트하세요.

Spring Event - 알림 기능 추가하기

  • 채널에 새로운 메시지가 등록되거나 2)권한이 변경된 경우 이벤트를 발행해 알림을 받을 수 있도록 구현합니다.
  • 채널에 새로운 메시지가 등록된 경우 알림을 받을 수 있도록 리팩토링하세요.
    • MessageCreatedEvent를 정의하고 새로운 메시지가 등록되면 이벤트를 발행하세요.
    • 사용자 별로 관심있는 채널의 알림만 받을 수 있도록 ReadStatus 엔티티에 채널 알림 여부 속성(notificationEnabled)을 추가하세요.
      • PRIVATE 채널은 알림 여부를 true로 초기화합니다.
      • PUBLIC 채널은 알림 여부를 false로 초기화합니다.
    • 알림 여부를 수정할 수 있게 ReadStatusUpdateRequest를 수정하세요.
      • 알림이 활성화 되어 있는 경우
      • 알림이 활성화 되어 있지 않은 경우
  • 사용자의 권한(Role)이 변경된 경우 알림을 받을 수 있도록 리팩토링하세요.
    • RoleUpdatedEvent를 정의하고 권한이 변경되면 이벤트를 발행하세요.
  • 알림 API를 구현하세요.
    • NotificationDto를 정의하세요.
      • receiverId: 알림을 수신할 User의 id입니다.
    • 알림 조회
      • 엔드포인트: GET /api/notifications
      • 요청
        • 헤더: 엑세스 토큰
      • 응답
        • 200 List
        • 401 ErrorResponse
      • 알림 확인
        • 엔드포인트: DELETE /api/notifications/{notificationId}
        • 요청
          • 헤더: 엑세스 토큰
        • 응답
          • 204 Void
          • 인증되지 않은 요청: 401 ErrorResponse
          • 인가되지 않은 요청: 403 ErrorResponse
            • 요청자 본인의 알림에 대해서만 수행할 수 있습니다.
          • 알림이 없는 경우: 404 ErrorResponse
  • 알림이 필요한 이벤트가 발행되었을 때 알림을 생성하세요.
    • 이벤트를 처리할 리스너를 구현하세요.
      • on(MessageCreatedEvent)
        • 해당 채널의 알림 여부를 활성화한 ReadStatus를 조회합니다.
        • 해당 ReadStatus의 사용자들에게 알림을 생성합니다.
        • 단, 해당 메시지를 보낸 사람은 알림 대상에서 제외합니다.
      • on(RoleUpdatedEvent)
        • 권한이 변경된 당사자에게 알림을 생성합니다.

비동기 적용하기

  • 비동기를 적용하기 위한 설정(AsyncConfig) 클래스를 구현하세요.
    • @EnableAsync 어노테이션을 활용하세요.
    • TaskExecutor를 Bean으로 등록하세요.
    • TaskDecorator를 활용해 MDC의 Request ID, SecurityContext의 인정 정보가 비동기 스레드에서도 유지되도록 구현하세요.
  • 앞서 구현한 Event Listener를 비동기적으로 처리하세요.
    • @async 어노테이션을 활용하세요.
  • 동기 처리와 비동기 처리 간 성능 차이를 비교해보세요.
    • 파일 업로드 로직에 의도적인 지연(Thread.sleep(…))을 발생시키세요.
    • 메시지 생성 API의 실행 시간을 측정해보세요.
      • @timed 어노테이션을 메소드에 추가합니다.
      • Actuator 설정을 추가합니다.
      • /actuator/metrics/message.create.async 에서 측정된 시간을 확인할 수 있습니다.
    • @EnableAsync를 활성화 / 비활성화 해보면서 동기 / 비동기 처리 간 응답 속도의 차이를 확인해보세요.

비동기 실패 처리하기

  • S3를 활용해 바이너리 데이터 저장 시 자동 재시도 매커니즘을 구축하세요.
    • Spring Retry를 위한 환경을 구성하세요.
      • org.springframework.retry:spring-retry 의존성을 추가하세요.
      • @EnableRetry 어노테이션을 활용해 Spring Retry를 활성화 하세요.
    • 바이너리 데이터를 저장하는 메소드에 @retryable 어노테이션을 사용해 재시도 정책(횟수, 대기 시간 등)을 설정하세요.
  • 재시도가 모두 실패했을 때 대응 전략을 구축하세요.
    • @recover 어노테이션을 활용하세요.
    • 실패 정보를 관리자에게 통지하세요.
      • 실패 정보에는 추후 디버깅을 위해 필요한 정보를 포함하세요.
        • 실패한 작업 이름
        • MDC의 Request ID
        • 실패 이유 (예외 메시지)

캐시 적용하기

  • Caffeine 캐시를 위한 환경을 구성하세요.
    • org.springframework.boot:spring-boot-starter-cache 의존성을 추가하세요.
    • com.github.ben-manes.caffeine:caffeine 의존성을 추가하세요.
    • application.yaml 설정 또는 Bean을 통해 캐시 Caffeine 캐시를 설정하세요.
  • @Cacheable 어노테이션을 활용해 캐시가 필요한 메소드에 적용하세요.
    • 사용자별 채널 목록 조회
    • 사용자별 알림 목록 조회
    • 사용자 목록 조회
  • 데이터 변경 시, 캐시를 갱신 또는 무효화하는 로직을 구현하세요.
    • @CacheEvict, @cACHEpUT, CacheManager 등을 활용하세요.
    • 예시:
      • 새로운 채널 추가/수정/삭제 → 채널 목록 캐시 무효화
      • 알림 추가/삭제 → 알림 목록 캐시 무효화
      • 사용자 추가/로그인/로그아웃 → 사용자 목록 캐시 무효화
  • 캐시 적용 전후의 차이를 비교해보세요.
    • 로그를 통해 SQL 실행 여부를 확인해보세요.
  • Spring Actuator를 활용해 캐시 관련 통계 지표를 확인해보세요.
    • Caffein Spec에 recordStats 옵션을 추가하세요.
    • /actuator/caches, /actuator/metrics/cache.* 를 통해 캐시 관련 데이터를 확인해보세요.

심화 요구사항

Spring Kafka 도입하기

  • Kafka 환경을 구성하세요.
    • Docker Compose를 활용해 Kafka를 구동하세요.
    • Spring Kafka 의존성을 추가하고, application.yml에 Kafka 설정을 추가하세요.
    • Spring Event를 Kafka로 발행하는 리스너를 구현하세요.
      • NotificationRequiredEventListener는 비활성화하세요.
      • KafkaProduceRequiredEventListener를 구현하세요.
      • Spring Event를 Kafka 메시지로 변환해 전송하는 중계 구조입니다.
    • Kafka Console을 통해 Kafka 이벤트가 잘 발행되는지 확인해보세요.
    • Kafka 토픽을 구독해 알림을 생성하는 리스너를 구현하세요.

Redis Cache 도입하기

  • Redis 환경을 구성하세요.
    • Docker Compose를 활용해 Redis를 구동하세요.
    • Redis 의존성을 추가하고, application.yml에 Redis 설정을 추가하세요.
    • 직렬화 설정을 위해 다음과 같이 Bean을 선언하세요.
  • DataGrip을 통해 Redis에 저장된 캐시 정보를 조회해보세요.

lkim0402 added 30 commits June 26, 2025 15:11
- repository  구현체를 application.yml 설정값을 통해 제어
- File*Repository 구현체의 파일을 저장할 디렉토리 경로를 application.yml 설정값을 통해 제어
- repository  구현체를 application.yml 설정값을 통해 제어
- File*Repository 구현체의 파일을 저장할 디렉토리 경로를 application.yml 설정값을 통해 제어
.orElseThrow(() -> ChannelNotFoundException.withId(channelId));
}

@Cacheable(value = "userChannelsCache", key = "#userId")
Copy link
Collaborator

Choose a reason for hiding this comment

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

캐시 설정

private final ObjectMapper objectMapper;

@KafkaListener(topics = "discodeit.MessageCreatedEvent")
@CacheEvict(value = "userNotificationsCache", allEntries = true)
Copy link
Collaborator

Choose a reason for hiding this comment

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

캐시 eviction 설정

);
binaryContentRepository.save(binaryContent);

publisher.publishEvent(new BinaryContentCreatedEvent(binaryContent.getId(), bytes));
Copy link
Collaborator

Choose a reason for hiding this comment

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

이벤트 발행

private final BinaryContentStorage binaryContentStorage;

@Async
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
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 +27 to +31
binaryContentStorage.put(event.id(), event.bytes());
binaryContentService.updateStatus(event.id(), BinaryContentStatus.SUCCESS);
} catch (Exception e) {
log.error("Binary Content 저장 실패: ", e);
binaryContentService.updateStatus(event.id(), BinaryContentStatus.FAIL);
Copy link
Collaborator

Choose a reason for hiding this comment

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

상태 변경 처리

jwtRegistry.invalidateJwtInformationByUserId(userId);

if (!pastRole.equals(newRole)) {
publisher.publishEvent(new RoleUpdatedEvent(pastRole, user));
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 +28 to +47
@Async
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void on(MessageCreatedEvent event) throws JsonProcessingException {
String payload = objectMapper.writeValueAsString(event);
kafkaTemplate.send("discodeit.MessageCreatedEvent", payload);
}

@Async
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void on(RoleUpdatedEvent event) throws JsonProcessingException {
String payload = objectMapper.writeValueAsString(event);
kafkaTemplate.send("discodeit.RoleUpdatedEvent", payload);

}

@Async
@EventListener
public void on(BinaryContentRecoverEvent event) throws JsonProcessingException {
String requestId = MDC.get("REQUEST_ID");
String payload = objectMapper.writeValueAsString(event);
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 +9 to +13
@Configuration
@EnableJpaAuditing
@EnableScheduling
@EnableCaching
@EnableRetry
Copy link
Collaborator

Choose a reason for hiding this comment

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

Retry 설정은 됐으나 누락

Comment on lines +46 to +55
@Timed("message.create.async")
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<MessageDto> create(
@RequestPart("messageCreateRequest") @Valid MessageCreateRequest messageCreateRequest,
@RequestPart(value = "attachments", required = false) List<MultipartFile> attachments
) {
log.info("메시지 생성 요청: request={}, attachmentCount={}",
messageCreateRequest, attachments != null ? attachments.size() : 0);

List<BinaryContentCreateRequest> attachmentRequests = Optional.ofNullable(attachments)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Timed 설정됨


// CacheConfig
@Bean
public RedisCacheConfiguration redisCacheConfiguration(ObjectMapper objectMapper) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

레디스 캐시 설정

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