Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ dependencies {
// Health Check
implementation 'org.springframework.boot:spring-boot-starter-actuator'

// Spring Retry 및 AOP (알림 저장 실패 재시도용)
implementation 'org.springframework.retry:spring-retry'
implementation 'org.springframework.boot:spring-boot-starter-aop'

testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/com/mr/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.retry.annotation.EnableRetry;

@EnableRetry
@EnableJpaAuditing
@SpringBootApplication
public class Application {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.mr.domain.notification.controller;

import com.mr.domain.notification.dto.res.NotificationListResponseDTO;
import com.mr.domain.notification.service.NotificationService;
import com.mr.global.apipayload.ApiResponse;
import com.mr.global.security.principal.CustomUserDetails;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/notifications")
@RequiredArgsConstructor
public class NotificationController {

private final NotificationService notificationService;

@GetMapping
public ApiResponse<NotificationListResponseDTO> getNotifications(
@AuthenticationPrincipal CustomUserDetails userDetails,
@PageableDefault(page = 0, size = 10, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable
){
Long userId = userDetails.getUserId();
NotificationListResponseDTO result = notificationService.getNotificationList(userId, pageable);
return ApiResponse.onSuccess(result);
}

// 알림 읽음 처리
@PatchMapping("/{notificationId}/read")
public ApiResponse<Void> readNotification(
@AuthenticationPrincipal CustomUserDetails userDetails,
@PathVariable Long notificationId
) {
Long userId = userDetails.getUserId();
notificationService.readNotification(userId, notificationId);
return ApiResponse.onSuccess(null);
}

// 알림 전체 읽음 처리
@PatchMapping("/read-all")
public ApiResponse<Void> readAllNotifications(
@AuthenticationPrincipal CustomUserDetails userDetails
) {
notificationService.readAllNotifications(userDetails.getUserId());
return ApiResponse.onSuccess(null);
}

// 안 읽은 알림 여부 확인 (사이드바 뱃지용)
@GetMapping("/unread-status")
public ApiResponse<Boolean> checkUnreadStatus(
@AuthenticationPrincipal CustomUserDetails userDetails
) {
boolean hasUnread = notificationService.checkUnreadNotification(userDetails.getUserId());
return ApiResponse.onSuccess(hasUnread);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.mr.domain.notification.dto.res;

import com.mr.domain.notification.entity.Notification;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Slice;

import java.util.List;
import java.util.stream.Collectors;

@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class NotificationListResponseDTO {
private List<NotificationResponseDTO> notificationList;
private Integer listSize;
private Boolean hasNext;
private Boolean isFirst;
private Boolean isLast;

public static NotificationListResponseDTO of(Slice<Notification> notificationSlice) {
List<NotificationResponseDTO> notificationDTOList = notificationSlice.getContent().stream()
.map(NotificationResponseDTO::from)
.collect(Collectors.toList());

return NotificationListResponseDTO.builder()
.notificationList(notificationDTOList)
.listSize(notificationDTOList.size())
.hasNext(notificationSlice.hasNext())
.isFirst(notificationSlice.isFirst())
.isLast(notificationSlice.isLast())
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.mr.domain.notification.dto.res;

import com.mr.domain.notification.entity.Notification;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class NotificationResponseDTO {

private Long notificationId;
private String title;
private String content;
private Boolean isRead;
private LocalDateTime createdAt;

public static NotificationResponseDTO from(Notification notification) {
return NotificationResponseDTO.builder()
.notificationId(notification.getId())
.title(notification.getTitle())
.content(notification.getContent())
.isRead(notification.isRead())
.createdAt(notification.getCreatedAt())
.build();
}
}
39 changes: 33 additions & 6 deletions src/main/java/com/mr/domain/notification/entity/Notification.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package com.mr.domain.notification.entity;

import com.mr.domain.user.entity.User;
import com.mr.global.entity.BaseTimeDeletedEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.AccessLevel;
import lombok.Builder;
Expand Down Expand Up @@ -36,8 +40,9 @@ public class Notification extends BaseTimeDeletedEntity{
private Long id;

// 유저 아이디
@Column(name = "user_id", nullable = false)
private Long userId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;

// 제목
@Column(name = "title", nullable = false, length = 100)
Expand All @@ -53,16 +58,20 @@ public class Notification extends BaseTimeDeletedEntity{


@Builder(access = AccessLevel.PRIVATE)
private Notification(Long userId, String title, String content) {
this.userId = userId;
private Notification(User user, String title, String content) {
Comment thread
rkdehdrbs7885-oss marked this conversation as resolved.
validateUser(user);
validateTitle(title);
validateContent(content);

this.user = user;
this.title = title;
this.content = content;
this.isRead = false;
}

public static Notification create(Long userId, String title, String content) {
public static Notification create(User user, String title, String content) {
return Notification.builder()
.userId(userId)
.user(user)
.title(title)
.content(content)
.build();
Expand All @@ -72,4 +81,22 @@ public static Notification create(Long userId, String title, String content) {
public void markAsRead() {
this.isRead = true;
}

private void validateUser(User user) {
if (user == null) {
throw new IllegalArgumentException("User는 필수입니다.");
}
}

private void validateTitle(String title) {
if (title == null || title.trim().isEmpty()) {
throw new IllegalArgumentException("Title은 필수입니다.");
}
}

private void validateContent(String content) {
if (content == null || content.trim().isEmpty()) {
throw new IllegalArgumentException("Content는 필수입니다.");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.mr.domain.notification.exception;

import com.mr.global.apipayload.code.BaseCode;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.http.HttpStatus;

@Getter
@AllArgsConstructor
public enum NotificationErrorStatus implements BaseCode {

// [403] 권한 에러
FORBIDDEN_NOTIFICATION(HttpStatus.FORBIDDEN, "NOTIFICATION_403_01", "해당 알림에 대한 권한이 없습니다."),

// [404] 리소스 없음
NOTIFICATION_NOT_FOUND(HttpStatus.NOT_FOUND, "NOTIFICATION_404_01", "존재하지 않는 알림입니다.");

private final HttpStatus status;
private final String code;
private final String message;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.mr.domain.notification.repository;

import com.mr.domain.notification.entity.Notification;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.LocalDateTime;
import java.util.Optional;

public interface NotificationRepository extends JpaRepository<Notification, Long> {

Page<Notification> findAllByUser_UserIdAndDeletedAtIsNull(Long userId, Pageable pageable);

Optional<Notification> findByIdAndDeletedAtIsNull(Long id);

@Modifying(clearAutomatically = true)
@Query("update Notification n set n.isRead = true where n.user.userId = :userId and n.isRead = false and n.deletedAt is null")
void bulkMarkAllAsReadByUserId(@Param("userId") Long userId);

// 유저에게 안 읽은 알림이 단 하나라도 존재하는지 확인 (사이드바 종 아이콘 뱃지용)
boolean existsByUser_UserIdAndIsReadFalseAndDeletedAtIsNull(Long userId);

// 중복 알림 방지용 쿼리 메서드
boolean existsByUser_UserIdAndTitleAndCreatedAtAfter(Long userId, String title, LocalDateTime time);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package com.mr.domain.notification.service;

import com.mr.domain.notification.entity.Notification;
import com.mr.domain.notification.repository.NotificationRepository;
import com.mr.domain.user.entity.User;
import com.mr.domain.user.exception.UserErrorStatus;
import com.mr.domain.user.repository.UserRepository;
import com.mr.global.apipayload.exception.GeneralException;
import com.mr.global.event.NotificationEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.time.LocalDateTime;

@Slf4j
@Component
@RequiredArgsConstructor
public class NotificationEventListener {

private final NotificationRepository notificationRepository;
private final UserRepository userRepository;

//누군가 NotificationEvent를 발행하면 이 메서드가 자동으로 실행
// DB 저장 실패 시 최대 3번 재시도 (1초 간격)
@Retryable(
retryFor = {Exception.class},
maxAttempts = 3,
backoff = @Backoff(delay = 1000)
)
@Async
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) // 메인 트랜잭션이 커밋된(AFTER_COMMIT) 이후에만 알림을 저장하도록 변경
@Transactional
public void handleNotificationEvent(NotificationEvent event) {
Comment thread
rkdehdrbs7885-oss marked this conversation as resolved.

// 중복 알림 검증 로직 (1분 이내 동일 제목 알림 무시)
LocalDateTime oneMinuteAgo = LocalDateTime.now().minusMinutes(1);
if (notificationRepository.existsByUser_UserIdAndTitleAndCreatedAtAfter(
event.getUserId(), event.getTitle(), oneMinuteAgo)) {
return; // 걸리면 바로 종료
}

User user = userRepository.findById(event.getUserId())
.orElseThrow(() -> new GeneralException(UserErrorStatus.USER_NOT_FOUND));

Notification notification = Notification.create(
user,
event.getTitle(),
event.getContent()
);

notificationRepository.save(notification);
Comment thread
rkdehdrbs7885-oss marked this conversation as resolved.
}

// 3번의 재시도 전부 실패했을 때 실행되는 '영구 보정 경로(Fallback)'
@Recover
public void recoverNotificationEvent(Exception e, NotificationEvent event) {
// 나중에 이 로그를 수집해서 슬랙 알림을 보내거나, 수동으로 복구할 수 있도록 단서를 남김
log.error("[알림 저장 최종 실패] userId: {}, title: {}, 원인: {}",
event.getUserId(), event.getTitle(), e.getMessage());
}
}
Loading
Loading