토이 프로젝트 스터디 #17

appti·2022년 7월 8일
0

토이 프로젝트 스터디 #17

  • 스터디 진행 날짜 : 7/8
  • 스터디 작업 날짜 : 7/4 ~ 7/8

토이 프로젝트 진행 사항

  • 기초적인 Spring Batch 적용

내용

Image

  • 업로드만 하고 사용하지 않는 이미지를 일괄 삭제하기 위해 추가
public interface ImageRepository extends JpaRepository<Image, Long> {
    List<Image> findByCreatedDateLessThanAndPostIsNull(LocalDateTime localDateTime);
}
  • 특정 기간 이전에 업로드했고 현재 사용되지 않는 이미지를 조회하기 위해 Repository에 메소드 추가
public class ImageService {
    
    ...

    public void deleteImageByBatch(LocalDateTime localDateTime) {
        imageRepository.findByCreatedDateLessThanAndPostIsNull(localDateTime)
                .stream()
                .forEach(image -> {
                    imageRepository.delete(image);
                });
    }
}
  • Batch를 통해 실행할 메소드를 Service에 추가
@Configuration
@EnableBatchProcessing
@RequiredArgsConstructor
public class ImageBatchConfig {

    private final JobBuilderFactory jobBuilderFactory;
    private final StepBuilderFactory stepBuilderFactory;
    private final ImageService imageService;

    @Bean
    public Job imageJob() {
        Job imageJob = jobBuilderFactory.get("imageJob")
                .start(imageStep())
                .build();

        return imageJob;
    }

    @Bean
    public Step imageStep() {
        return stepBuilderFactory.get("imageStep")
                .tasklet((contribution, chunkContext) -> {
                    imageService.deleteImageByBatch(LocalDateTime.now().minusDays(7));
                    return RepeatStatus.FINISHED;
                }).build();
    }

    @Bean
    public ImageBatchScheduler imageBatchScheduler(JobLauncher jobLauncher) {
        return new ImageBatchScheduler(jobLauncher, imageJob());
    }
}
  • Batch 관련 설정을 Config에 추가
@RequiredArgsConstructor
public class ImageBatchScheduler {

    private final JobLauncher jobLauncher;
    private final Job imageJob;

    @Scheduled(cron = "0 */5 * * * *")
    public void runImageJob() {
        Map<String, JobParameter> confMap = new HashMap<>();
        confMap.put("time", new JobParameter(System.currentTimeMillis()));

        JobParameters jobParameters = new JobParameters(confMap);

        try {
            jobLauncher.run(imageJob, jobParameters);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
  • 이미지 관련 Batch 작업을 수행하는 코드 작성

Post

  • 좋아요 및 조회수를 일괄로 업데이트하기 위해 추가
public class PostService {
    
    ...
    
    public void updatePostValueByBatch() {
        List<Post> posts = postRepository.findAll();

        posts.stream().forEach(post -> {
            PostValue postValue = postValueRepository.findById(post.getId()).orElseThrow(PostValueNotFoundException::new);
            post.updatePostValue(postValue);
        });
    }
}
  • Batch를 통해 실행할 메소드를 Service에 추가
@Configuration
@EnableBatchProcessing
@RequiredArgsConstructor
public class PostValueBatchConfig {

    private final JobBuilderFactory jobBuilderFactory;
    private final StepBuilderFactory stepBuilderFactory;
    private final PostService postService;

    @Bean
    public Job postValueJob() {
        Job imageJob = jobBuilderFactory.get("postValueJob")
                .start(postValueStep())
                .build();

        return imageJob;
    }

    @Bean
    public Step postValueStep() {
        return stepBuilderFactory.get("postValueStep")
                .tasklet((contribution, chunkContext) -> {
                    postService.updatePostValueByBatch();
                    return RepeatStatus.FINISHED;
                }).build();
    }

    @Bean
    public PostValueBatchScheduler postValueBatchScheduler(JobLauncher jobLauncher) {
        return new PostValueBatchScheduler(jobLauncher, postValueJob());
    }
}
  • Batch 관련 설정을 Config에 추가

개선사항

  • Spring Batch에 대한 가장 기초적인 방식으로 사용
    • 이미지 수나 게시글 수가 많아질 수록 의미가 퇴색될 것이라 예상됨
    • chunk 단위로 쪼개 처리하는 방식을 사용하는 편이 좋아 보임
      • Spring Batch에 대한 학습 필요
  • Batch 작업을 수행하는 스케쥴러 코드에 중복되는 코드가 매우 많음
    • 공통 처리 필요
profile
안녕하세요

0개의 댓글