|
| 1 | +package com.team.buddyya.job.feed; |
| 2 | + |
| 3 | +import java.util.concurrent.ThreadLocalRandom; |
| 4 | +import java.util.concurrent.atomic.AtomicInteger; |
| 5 | +import org.springframework.batch.item.ItemReader; |
| 6 | +import org.springframework.jdbc.core.JdbcTemplate; |
| 7 | + |
| 8 | +public class FeedItemReader implements ItemReader<FeedJobDTO> { |
| 9 | + |
| 10 | + private final JdbcTemplate jdbcTemplate; |
| 11 | + private final int totalCount; |
| 12 | + private final AtomicInteger counter = new AtomicInteger(0); |
| 13 | + |
| 14 | + private Long minStudentId; |
| 15 | + private Long maxStudentId; |
| 16 | + private Long minUniversityId; |
| 17 | + private Long maxUniversityId; |
| 18 | + |
| 19 | + public FeedItemReader(JdbcTemplate jdbcTemplate, int totalCount) { |
| 20 | + this.jdbcTemplate = jdbcTemplate; |
| 21 | + this.totalCount = totalCount; |
| 22 | + } |
| 23 | + |
| 24 | + @Override |
| 25 | + public FeedJobDTO read() throws Exception { |
| 26 | + if (minStudentId == null) { |
| 27 | + // Student, University 테이블의 데이터 존재 여부 및 ID 범위 초기화 |
| 28 | + if (jdbcTemplate.queryForObject("SELECT COUNT(1) FROM student", Long.class) == 0) { |
| 29 | + throw new IllegalStateException("Prerequisite data (Student) is missing."); |
| 30 | + } |
| 31 | + this.minStudentId = jdbcTemplate.queryForObject("SELECT MIN(id) FROM student", Long.class); |
| 32 | + this.maxStudentId = jdbcTemplate.queryForObject("SELECT MAX(id) FROM student", Long.class); |
| 33 | + if (jdbcTemplate.queryForObject("SELECT COUNT(1) FROM university", Long.class) == 0) { |
| 34 | + throw new IllegalStateException("Prerequisite data (University) is missing."); |
| 35 | + } |
| 36 | + this.minUniversityId = jdbcTemplate.queryForObject("SELECT MIN(id) FROM university", Long.class); |
| 37 | + this.maxUniversityId = jdbcTemplate.queryForObject("SELECT MAX(id) FROM university", Long.class); |
| 38 | + } |
| 39 | + |
| 40 | + if (counter.get() >= totalCount) { |
| 41 | + return null; |
| 42 | + } |
| 43 | + |
| 44 | + int currentCount = counter.incrementAndGet(); |
| 45 | + long randomStudentId = ThreadLocalRandom.current().nextLong(minStudentId, maxStudentId + 1); |
| 46 | + long randomUniversityId = ThreadLocalRandom.current().nextLong(minUniversityId, maxUniversityId + 1); |
| 47 | + // Category는 데이터가 적다고 가정하고 SQL로 랜덤 조회, 많아진다면 동일하게 MIN/MAX 방식으로 변경 |
| 48 | + Long randomCategoryId = jdbcTemplate.queryForObject("SELECT id FROM category ORDER BY RAND() LIMIT 1", |
| 49 | + Long.class); |
| 50 | + |
| 51 | + return FeedJobDTO.builder() |
| 52 | + .title("피드 제목 " + currentCount) |
| 53 | + .content("피드 내용입니다. " + currentCount) |
| 54 | + .profileVisible(ThreadLocalRandom.current().nextBoolean()) |
| 55 | + .studentId(randomStudentId) |
| 56 | + .categoryId(randomCategoryId) |
| 57 | + .universityId(randomUniversityId) |
| 58 | + .build(); |
| 59 | + } |
| 60 | +} |
0 commit comments