Skip to content

Commit ebc3c17

Browse files
committed
feat: 월간 랭킹 리더 및 주간 랭킹 리더 추가
1 parent e27d520 commit ebc3c17

2 files changed

Lines changed: 239 additions & 0 deletions

File tree

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
package com.loopers.batch.job.ranking.reader;
2+
3+
import com.loopers.batch.domain.RankingWeightReader;
4+
import com.loopers.dto.ProductMetricsSummary;
5+
import com.loopers.dto.RankedProduct;
6+
import lombok.extern.slf4j.Slf4j;
7+
import org.springframework.batch.core.configuration.annotation.StepScope;
8+
import org.springframework.batch.item.ItemReader;
9+
import org.springframework.beans.factory.annotation.Value;
10+
import org.springframework.stereotype.Component;
11+
12+
import java.time.LocalDate;
13+
import java.time.YearMonth;
14+
import java.time.format.DateTimeFormatter;
15+
import java.util.Comparator;
16+
import java.util.Iterator;
17+
import java.util.List;
18+
import java.util.Map;
19+
import java.util.stream.Collectors;
20+
21+
@Slf4j
22+
@StepScope
23+
@Component
24+
public class MonthlyRankingReader implements ItemReader<RankedProduct> {
25+
26+
private final ProductMetricsJpaRepository metricsRepository;
27+
private final RankingWeightReader rankingWeightReader;
28+
private Iterator<RankedProduct> iterator;
29+
private boolean initialized = false;
30+
31+
@Value("#{jobParameters['yearMonth']}")
32+
private String yearMonthStr;
33+
34+
private static final DateTimeFormatter YEAR_MONTH_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM");
35+
private static final int TOP_N = 100;
36+
37+
public MonthlyRankingReader(ProductMetricsJpaRepository metricsRepository,
38+
RankingWeightReader rankingWeightReader) {
39+
this.metricsRepository = metricsRepository;
40+
this.rankingWeightReader = rankingWeightReader;
41+
}
42+
43+
@Override
44+
public RankedProduct read() {
45+
if (!initialized) {
46+
initialize();
47+
initialized = true;
48+
}
49+
50+
if (iterator != null && iterator.hasNext()) {
51+
return iterator.next();
52+
}
53+
return null;
54+
}
55+
56+
private void initialize() {
57+
YearMonth yearMonth = parseYearMonth();
58+
LocalDate startDate = yearMonth.atDay(1);
59+
LocalDate endDate = yearMonth.atEndOfMonth();
60+
61+
log.info("월간 랭킹 Reader 초기화: yearMonth={}, startDate={}, endDate={}", yearMonth, startDate, endDate);
62+
63+
List<ProductMetricsSummary> summaries = metricsRepository.findAllByProductIdAndDateBetween(startDate, endDate);
64+
65+
if (summaries.isEmpty()) {
66+
log.warn("집계할 메트릭 데이터가 없습니다.");
67+
iterator = List.<RankedProduct>of().iterator();
68+
return;
69+
}
70+
71+
// 상품별 집계
72+
Map<Long, double[]> aggregatedMap = summaries.stream()
73+
.collect(Collectors.groupingBy(
74+
ProductMetricsSummary::getProductId,
75+
Collectors.collectingAndThen(
76+
Collectors.toList(),
77+
list -> {
78+
double[] sums = new double[3];
79+
for (ProductMetricsSummary s : list) {
80+
sums[0] += s.getLikeCount();
81+
sums[1] += s.getStockCount();
82+
sums[2] += s.getViewCount();
83+
}
84+
return sums;
85+
}
86+
)
87+
));
88+
89+
// 점수 계산 및 정렬
90+
List<RankedProduct> rankedProducts = aggregatedMap.entrySet().stream()
91+
.map(entry -> {
92+
double[] sums = entry.getValue();
93+
double score = rankingWeightReader.calculateTotalScore(
94+
(int) sums[0], (int) sums[1], (int) sums[2]
95+
);
96+
return new RankedProduct(entry.getKey(), score);
97+
})
98+
.sorted(Comparator.comparingDouble(RankedProduct::score).reversed())
99+
.limit(TOP_N)
100+
.toList();
101+
102+
log.info("월간 랭킹 Reader 완료: 집계 상품 수={}, TOP-N={}", aggregatedMap.size(), rankedProducts.size());
103+
104+
iterator = rankedProducts.iterator();
105+
}
106+
107+
private YearMonth parseYearMonth() {
108+
if (yearMonthStr != null && !yearMonthStr.isBlank()) {
109+
return YearMonth.parse(yearMonthStr, YEAR_MONTH_FORMATTER);
110+
}
111+
// 기본값: 이번 달
112+
return YearMonth.now();
113+
}
114+
}
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
package com.loopers.batch.job.ranking.reader;
2+
3+
import com.loopers.batch.domain.RankingWeightReader;
4+
import com.loopers.dto.ProductMetricsSummary;
5+
import com.loopers.dto.RankedProduct;
6+
import com.loopers.infrastructure.metrics.ProductMetricsJpaRepository;
7+
import lombok.extern.slf4j.Slf4j;
8+
import org.springframework.batch.core.configuration.annotation.StepScope;
9+
import org.springframework.batch.item.ItemReader;
10+
import org.springframework.beans.factory.annotation.Value;
11+
import org.springframework.stereotype.Component;
12+
13+
import java.time.DayOfWeek;
14+
import java.time.LocalDate;
15+
import java.time.format.DateTimeFormatter;
16+
import java.util.Comparator;
17+
import java.util.Iterator;
18+
import java.util.List;
19+
import java.util.Map;
20+
import java.util.stream.Collectors;
21+
22+
@Slf4j
23+
@StepScope
24+
@Component
25+
public class WeeklyRankingReader implements ItemReader<RankedProduct> {
26+
27+
private final ProductMetricsJpaRepository metricsRepository;
28+
private final RankingWeightReader rankingWeightReader;
29+
private Iterator<RankedProduct> iterator;
30+
private boolean initialized = false;
31+
32+
@Value("#{jobParameters['startDate']}")
33+
private String startDateStr;
34+
35+
@Value("#{jobParameters['endDate']}")
36+
private String endDateStr;
37+
38+
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
39+
private static final int TOP_N = 100;
40+
41+
public WeeklyRankingReader(ProductMetricsJpaRepository metricsRepository,
42+
RankingWeightReader rankingWeightReader) {
43+
this.metricsRepository = metricsRepository;
44+
this.rankingWeightReader = rankingWeightReader;
45+
}
46+
47+
@Override
48+
public RankedProduct read() {
49+
if (!initialized) {
50+
initialize();
51+
initialized = true;
52+
}
53+
54+
if (iterator != null && iterator.hasNext()) {
55+
return iterator.next();
56+
}
57+
return null;
58+
}
59+
60+
private void initialize() {
61+
LocalDate startDate = parseStartDate();
62+
LocalDate endDate = parseEndDate();
63+
64+
log.info("주간 랭킹 Reader 초기화: startDate={}, endDate={}", startDate, endDate);
65+
66+
List<ProductMetricsSummary> summaries = metricsRepository.findAllByProductIdAndDateBetween(startDate, endDate);
67+
68+
if (summaries.isEmpty()) {
69+
log.warn("집계할 메트릭 데이터가 없습니다.");
70+
iterator = List.<RankedProduct>of().iterator();
71+
return;
72+
}
73+
74+
// 상품별 집계
75+
Map<Long, double[]> aggregatedMap = summaries.stream()
76+
.collect(Collectors.groupingBy(
77+
ProductMetricsSummary::getProductId,
78+
Collectors.collectingAndThen(
79+
Collectors.toList(),
80+
list -> {
81+
double[] sums = new double[3];
82+
for (ProductMetricsSummary s : list) {
83+
sums[0] += s.getLikeCount();
84+
sums[1] += s.getStockCount();
85+
sums[2] += s.getViewCount();
86+
}
87+
return sums;
88+
}
89+
)
90+
));
91+
92+
// 점수 계산 및 정렬
93+
List<RankedProduct> rankedProducts = aggregatedMap.entrySet().stream()
94+
.map(entry -> {
95+
double[] sums = entry.getValue();
96+
double score = rankingWeightReader.calculateTotalScore(
97+
(int) sums[0], (int) sums[1], (int) sums[2]
98+
);
99+
return new RankedProduct(entry.getKey(), score);
100+
})
101+
.sorted(Comparator.comparingDouble(RankedProduct::score).reversed())
102+
.limit(TOP_N)
103+
.toList();
104+
105+
log.info("주간 랭킹 Reader 완료: 집계 상품 수={}, TOP-N={}", aggregatedMap.size(), rankedProducts.size());
106+
107+
iterator = rankedProducts.iterator();
108+
}
109+
110+
private LocalDate parseStartDate() {
111+
if (startDateStr != null && !startDateStr.isBlank()) {
112+
return LocalDate.parse(startDateStr, DATE_FORMATTER);
113+
}
114+
// 기본값: 이번 주 월요일
115+
return LocalDate.now().with(DayOfWeek.MONDAY);
116+
}
117+
118+
private LocalDate parseEndDate() {
119+
if (endDateStr != null && !endDateStr.isBlank()) {
120+
return LocalDate.parse(endDateStr, DATE_FORMATTER);
121+
}
122+
// 기본값: 이번 주 일요일
123+
return LocalDate.now().with(DayOfWeek.SUNDAY);
124+
}
125+
}

0 commit comments

Comments
 (0)