Skip to content

Commit

Permalink
Merge pull request #31 from nhnacademy-be6-5ritang/feature/schedulerE…
Browse files Browse the repository at this point in the history
…xception

feature "coupon 기간만료 scheduler logic 예외처리"
  • Loading branch information
kihoo-ni authored Aug 1, 2024
2 parents 06234b7 + 199a27b commit 7742cf6
Show file tree
Hide file tree
Showing 5 changed files with 114 additions and 34 deletions.
8 changes: 8 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,14 @@
</dependency>


<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

Expand All @@ -12,6 +13,7 @@
@EnableScheduling
@EnableFeignClients
@EnableWebSecurity
@EnableAspectJAutoProxy
public class BookStoreCouponApplication {

public static void main(String[] args) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.nhnacademy.bookstorecoupon.userandcoupon.exception;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
public class retrytest {

private static final int MAX_RETRY_ATTEMPTS = 3;
private static final int RETRY_DELAY_MS = 5000; // 5초 대기

@Scheduled(cron = "0 55 19 * * *")
public void testScheduler() {
log.warn("기한만료 쿠폰 체크로직 발동");

try {
// 실제 로직 수행
executeLogic();
} catch (Exception e) {
log.error("기한만료 쿠폰 체크로직 실행 중 오류 발생", e);
// 재시도 로직 호출
retryTest(1);
}
}

private void retryTest(int attempt) {
if (attempt > MAX_RETRY_ATTEMPTS) {
log.error("최대 재시도 횟수 초과");
// 재시도 실패 알림 전송 또는 다른 처리
return;
}

try {
Thread.sleep(RETRY_DELAY_MS); // 대기 시간
log.warn("재시도 - 시도 " + attempt);
// 새로운 스레드 대신 스케줄링을 사용
new Thread(() -> {
try {
executeLogic();
} catch (Exception e) {
log.error("재시도 중 오류 발생", e);
retryTest(attempt + 1); // 다음 시도
}
}).start();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("재시도 중 오류 발생", e);
}
}

private void executeLogic() throws Exception {
// 실제 로직 수행
throw new Exception("Test exception");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@
@Slf4j
public class UserAndCouponServiceImpl implements UserAndCouponService {

private static final int MAX_RETRY_ATTEMPTS = 3;
private static final int RETRY_DELAY_MS = 5000; // 5초 대기

private final UserAndCouponRepository userAndCouponRepository;
private final BookCouponRepository bookCouponRepository;
private final CategoryCouponRepository categoryCouponRepository;
Expand Down Expand Up @@ -81,9 +84,25 @@ public void createUserWelcomeCouponIssue(Long userId) {
}

// 쿠폰 만료처리 스케줄링 매일 새벽 2시 시작 설정
@Override
@Scheduled(cron = "0 0 2 * * *")
public void findExpiredCouponsScheduler() {
log.warn("기한만료 쿠폰 스케쥴러 시작");

try {
// 실제 로직 수행
findExpiredCoupons();
} catch (Exception e) {
log.error("기한만료 쿠폰 체크로직 실행 중 오류 발생", e);
// 재시도 로직 호출
retryLogic(1);
}


}

@Override
public void findExpiredCoupons() {

log.warn("기한만료 쿠폰 체크로직 발동");
LocalDateTime now = LocalDateTime.now();

Expand All @@ -93,10 +112,35 @@ public void findExpiredCoupons() {
for (UserAndCoupon coupon : expiredCoupons) {
coupon.update(coupon.getExpiredDate(), true);
}

log.warn("기한만료 쿠폰 체크로직 실행완료");
}

private void retryLogic(int attempt) {
if (attempt > MAX_RETRY_ATTEMPTS) {
log.error("최대 재시도 횟수 초과");
// 재시도 실패 알림 전송 또는 다른 처리
return;
}

try {
Thread.sleep(RETRY_DELAY_MS); // 대기 시간
log.warn("재시도 - 시도 " + attempt);

new Thread(() -> {
try {
findExpiredCoupons();
} catch (Exception e) {
log.error("재시도 중 오류 발생", e);
retryLogic(attempt + 1); // 다음 시도
}
}).start();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("재시도 중 오류 발생", e);
}
}



@Override
@Scheduled(cron = "0 0 1 * * *")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,38 +122,7 @@ void createUserWelcomeCouponIssue_ShouldThrowException_WhenPolicyNotFound() {
}


// @Test
// void findExpiredCoupons_ShouldUpdateExpiredCoupons() {
// // 현재 시간 고정
// LocalDateTime now = LocalDateTime.now();
// UserAndCoupon expiredCoupon = UserAndCoupon.builder()
// .couponPolicy(CouponPolicy.builder()
// .minOrderPrice(BigDecimal.valueOf(100))
// .salePrice(BigDecimal.valueOf(100))
// .maxSalePrice(null)
// .saleRate(null)
// .type("welcome")
// .build())
// .userId(1L)
// .isUsed(false)
// .expiredDate(now.minusDays(1))
// .issueDate(now.minusDays(10))
// .build();
//
// // Stub the repository method to return the list with the expiredCoupon
// when(userAndCouponRepository.findByExpiredDateBeforeAndIsUsedIsFalse(now))
// .thenReturn(Collections.singletonList(expiredCoupon));
//
// // Call the method under test
// userAndCouponService.findExpiredCoupons();
//
// // Verify that save was called with the updated coupon
// verify(userAndCouponRepository, times(1)).save(argThat(coupon ->
// coupon.getIsUsed() == true &&
// coupon.getExpiredDate().isBefore(now) &&
// coupon.getIssueDate().isBefore(now)
// ));
// }

@Test
void issueBirthdayCoupon_ShouldIssueCoupons_WhenUsersExist() {
LocalDate today = LocalDate.now();
Expand Down

0 comments on commit 7742cf6

Please sign in to comment.