-
Notifications
You must be signed in to change notification settings - Fork 16
[권용진] Sprint11 #158
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: 권용진
Are you sure you want to change the base?
[권용진] Sprint11 #158
Conversation
| @Async("taskExecutor") | ||
| @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) | ||
| @Transactional | ||
| public void handleBinaryContentCreated(S3UploadEvent event) { | ||
| log.info("listener thread={}", Thread.currentThread().getName()); | ||
| BinaryContent binaryContent = binaryContentRepository.findById(event.binaryContentId()) | ||
| .orElseThrow(BinaryContentNotFoundException::new); | ||
|
|
||
| try { | ||
| binaryContentStorage.put(event.binaryContentId(), event.bytes()); | ||
| binaryContentService.updateStatus(event.binaryContentId(), BinaryContentStatus.SUCCESS); | ||
| log.debug("BinaryContent 저장 성공: id={}", event.binaryContentId()); | ||
| } catch (Exception e) { | ||
| binaryContentService.updateStatus(event.binaryContentId(), BinaryContentStatus.FAIL); | ||
| log.error("BinaryContent 저장 실패: id={}, error={}", event.binaryContentId(), e.getMessage(), e); | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
상태 변경 처리
- BinaryContentStatus.SUCCESS
- BinaryContentStatus.FAIL
| @Transactional | ||
| @Override | ||
| public UserDto updateRoleInternal(RoleUpdateRequest request) { | ||
| UUID userId = request.userId(); | ||
| User user = userRepository.findById(userId) | ||
| .orElseThrow(() -> UserNotFoundException.withId(userId)); | ||
|
|
||
| Role oldRole = user.getRole(); | ||
| Role newRole = request.newRole(); | ||
| user.updateRole(newRole); | ||
|
|
||
| jwtRegistry.invalidateJwtInformationByUserId(userId); | ||
| eventPublisher.publishEvent(new RoleUpdatedEvent(user, oldRole, newRole)); | ||
| return userMapper.toDto(user); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이벤트 발행
| public UserDto create(UserCreateRequest userCreateRequest, | ||
| Optional<BinaryContentCreateRequest> optionalProfileCreateRequest) { | ||
| log.debug("사용자 생성 시작: {}", userCreateRequest); | ||
|
|
||
| String username = userCreateRequest.username(); | ||
| String email = userCreateRequest.email(); | ||
|
|
||
| if (userRepository.existsByEmail(email)) { | ||
| throw UserAlreadyExistsException.withEmail(email); | ||
| } | ||
| if (userRepository.existsByUsername(username)) { | ||
| throw UserAlreadyExistsException.withUsername(username); | ||
| } | ||
|
|
||
| BinaryContent nullableProfile = optionalProfileCreateRequest | ||
| .map(profileRequest -> { | ||
| String fileName = profileRequest.fileName(); | ||
| String contentType = profileRequest.contentType(); | ||
| byte[] bytes = profileRequest.bytes(); | ||
| BinaryContent binaryContent = new BinaryContent(fileName, (long) bytes.length, | ||
| contentType); | ||
| binaryContentRepository.save(binaryContent); | ||
| eventPublisher.publishEvent(new S3UploadEvent(binaryContent.getId(), bytes)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이벤트 발행
- S3UploadEvent는 서비스 종속적이라 BinaryContentCreatedEvent 로 네이밍 변경되는 편이 좋아보입니다.
| private final BinaryContentService binaryContentService; | ||
|
|
||
| @Async("taskExecutor") | ||
| @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이벤트 소비 처리
| eventPublisher.publishEvent(new MessageCreatedEvent(message)); | ||
| log.info("메시지 생성 완료: id={}, channelId={}", message.getId(), channelId); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이벤트 발행
| @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT) | ||
| public void on(RoleUpdatedEvent event) { | ||
|
|
||
| String title = "권한이 변경되었습니다."; | ||
| String content = event.oldRole().toString() + "->" + event.newRole().toString(); | ||
| notificationService.create(event.user().getId(), title, content); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
메세지 소비
| import org.springframework.security.core.context.SecurityContextHolder; | ||
|
|
||
| @Configuration | ||
| @EnableAsync |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
비동기 설정
|
|
||
| private final MessageService messageService; | ||
|
|
||
| @Timed("message.create.async") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
메소드 별 실행 통계
| import org.springframework.retry.annotation.EnableRetry; | ||
|
|
||
| @Configuration | ||
| @EnableRetry |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
재처리 설정
| return userDto; | ||
| } | ||
|
|
||
| @Cacheable(cacheNames = USERS_ALL, key = "'USER_ALL'", sync = true) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
로컬 캐시 적용
| @Slf4j | ||
| @RequiredArgsConstructor | ||
| @Component | ||
| public class KafkaProduceRequiredEventListener { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
카프카를 통한 이벤트 발행
| record.headers().add(new RecordHeader("x-event-type", | ||
| payload.getClass().getSimpleName().getBytes(StandardCharsets.UTF_8))); | ||
|
|
||
| kafkaTemplate.send(record).whenComplete((result, ex) -> { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이벤트 발행
| @Configuration | ||
| @EnableCaching |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
CacheConfig
| private final UserRepository userRepository; | ||
| private final ChannelMapper channelMapper; | ||
|
|
||
| @CacheEvict(cacheNames = CHANNELS_BY_USER, allEntries = true) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
캐시 만료
✅ 기본 요구사항
Spring Event - 파일 업로드 로직 분리하기
디스코드잇은 BinaryContent의 메타 데이터(DB) 와 바이너리 데이터(FileSystem/S3) 를 분리해 저장합니다.
만약 지금처럼 두 로직이 하나의 트랜잭션으로 묶인 경우, 트랜잭션을 과도하게 오래 점유할 수 있는 문제가 있습니다.
따라서 Spring Event를 활용해 메타 데이터 저장 트랜잭션으로부터 바이너리 데이터 저장 로직을 분리하여,
메타데이터 저장 트랜잭션이 종료되면 바이너리 데이터를 저장하도록 변경합니다.
BinaryContentStorage.put을 직접 호출하는 대신BinaryContentCreatedEvent를 발행하세요.BinaryContentCreatedEvent를 정의하세요.다음의 메서드에서
BinaryContentStorage를 호출하는 대신BinaryContentCreatedEvent를 발행하세요.UserService.create/updateMessageService.createBinaryContentService.createApplicationEventPublisher를 활용하세요.이벤트를 받아 실제 바이너리 데이터를 저장하는 리스너를 구현하세요.
BinaryContentStorage를 통해 바이너리 데이터를 저장하세요.바이너리 데이터 저장 성공 여부를 알 수 있도록 메타데이터를 리팩토링하세요.
BinaryContent에 바이너리 데이터 업로드 상태 속성(status)을 추가하세요.PROCESSING: 업로드 중 (기본값)SUCCESS: 업로드 완료FAIL: 업로드 실패BinaryContent의 상태를 업데이트하는 메서드를 정의하세요.바이너리 데이터 저장 성공 여부를 메타데이터에 반영하세요.
BinaryContent.status를SUCCESS로 업데이트하세요.BinaryContent.status를FAIL로 업데이트하세요.Spring Event - 알림 기능 추가하기
채널에 새로운 메시지가 등록된 경우 알림을 받을 수 있도록 리팩토링하세요.
MessageCreatedEvent를 정의하고 새로운 메시지가 등록되면 이벤트를 발행하세요.ReadStatus엔티티에채널 알림 여부 속성(
notificationEnabled)을 추가하세요.true로 초기화합니다.false로 초기화합니다.ReadStatusUpdateRequest를 수정하세요.사용자의 권한(Role)이 변경된 경우 알림을 받을 수 있도록 리팩토링하세요.
RoleUpdatedEvent를 정의하고 권한이 변경되면 이벤트를 발행하세요.알림 API를 구현하세요.
NotificationDto를 정의하세요.receiverId: 알림을 수신할 사용자의 ID입니다.알림 조회
엔드포인트:
GET /api/notifications요청: 헤더에 Access Token 포함
응답:
200→List<NotificationDto>401→ErrorResponse알림 확인
엔드포인트:
DELETE /api/notifications/{notificationId}요청: 헤더에 Access Token 포함
응답:
204→Void401 ErrorResponse403 ErrorResponse404 ErrorResponse알림이 필요한 이벤트가 발행되었을 때 알림을 생성하세요.
on(MessageCreatedEvent)해당 채널의 알림 여부를 활성화한
ReadStatus를 조회합니다.해당
ReadStatus의 사용자들에게 알림을 생성합니다.단, 해당 메시지를 보낸 사람은 알림 대상에서 제외합니다.
알림 예시
title: "보낸 사람 (#채널명)"content: "메시지 내용"on(RoleUpdatedEvent)권한이 변경된 당사자에게 알림을 생성합니다.
알림 예시
title: "권한이 변경되었습니다."content: "USER -> CHANNEL_MANAGER"비동기 적용하기
비동기를 적용하기 위한 설정(
AsyncConfig) 클래스를 구현하세요.@EnableAsync어노테이션을 활용하세요.TaskExecutor를 Bean으로 등록하세요.TaskDecorator를 활용해 MDC의 Request ID, SecurityContext의 인증 정보가비동기 스레드에서도 유지되도록 구현하세요.
앞서 구현한 Event Listener를 비동기적으로 처리하세요.
@Async어노테이션을 활용하세요.동기 처리와 비동기 처리 간 성능 차이를 비교해보세요.
Thread.sleep(...))을 발생시키세요.메시지 생성 API의 실행 시간을 측정해보세요.
@Timed어노테이션을 메서드에 추가합니다./actuator/metrics/message.create.async에서 측정된 시간을 확인할 수 있습니다.@EnableAsync를 활성화/비활성화하여 동기 / 비동기 처리 속도 차이를 비교해보세요.비동기 실패 처리하기
따라서 비동기로 처리하는 로직은 자동 재시도 전략을 통해 더 견고하게 구현해야 합니다.
또한 실패하더라도 그 사실을 명확하게 기록해두어야 에러에 대응할 수 있습니다.
S3를 활용해 바이너리 데이터 저장 시 자동 재시도 매커니즘을 구축하세요.
org.springframework.retry:spring-retry의존성을 추가하세요.@EnableRetry어노테이션으로 Spring Retry를 활성화하세요.@Retryable을 적용해 재시도 정책(횟수, 대기 시간 등) 을 설정하세요.재시도가 모두 실패했을 때 대응 전략을 구축하세요.
@Recover어노테이션을 활용하세요.실패 정보를 관리자에게 통지하세요.
알림 내용 예시
실패 정보에는 추후 디버깅을 위한 다음 항목들을 포함하세요.
캐시 적용하기
Caffeine 캐시를 위한 환경을 구성하세요.
org.springframework.boot:spring-boot-starter-cache의존성을 추가하세요.com.github.ben-manes.caffeine:caffeine의존성을 추가하세요.application.yaml설정 또는 Bean을 통해 Caffeine 캐시를 설정하세요.@Cacheable어노테이션을 활용해 캐시가 필요한 메서드에 적용하세요.데이터 변경 시 캐시를 갱신 또는 무효화하는 로직을 구현하세요.
@CacheEvict,@CachePut,CacheManager등을 활용하세요.예시:
캐시 적용 전후의 차이를 비교해보세요.
Spring Actuator를 활용해 캐시 관련 통계 지표를 확인하세요.
recordStats옵션을 추가하세요./actuator/caches,/actuator/metrics/cache.*를 통해 캐시 관련 데이터를 확인하세요.Spring Kafka 도입하기
알림 서비스에서는 서버 외부의 이벤트를 소비할 수 있도록 구성해야 합니다.
Kafka 환경을 구성하세요.
application.yaml에 Kafka 설정을 추가하세요.implementation 'org.springframework.kafka:spring-kafka'Spring Event를 Kafka로 발행하는 리스너를 구현하세요.
NotificationRequiredEventListener는 비활성화하세요.KafkaProduceRequiredEventListener를 구현하세요.(메인 서비스 → Kafka → 알림 서비스)
Kafka Console을 통해 Kafka 이벤트가 잘 발행되는지 확인하세요.
broker 컨테이너 쉘 접속
docker exec -it -w /opt/kafka/bin broker sh토픽 리스트 확인 (실행 위치:
/opt/kafka/bin)예시 출력:
특정 토픽 이벤트 구독 및 대기 (실행 위치:
/opt/kafka/bin)Kafka 토픽을 구독해 알림을 생성하는 리스너를 구현하세요.
NotificationRequiredTopicListener를 구현하세요.@EventListener기반 로직을 제거하고@KafkaListener기반으로 대체하세요.Redis Cache 도입하기
Redis 환경을 구성하세요.
Docker Compose를 활용해 Redis를 구동하세요.
application.yml에 Redis 설정을 추가하세요.Bean을 선언하세요.