[Spring]JobRunr libary 사용

Java에서 백그라운드 Job를 실행시키는 라이브러리 이다. 실행 시키고 잊는 처리를 하기에 접합하다. python에서의 Celery와 같은 역할을 하지만 더 많은 기능을 제공한다.

Spring에서의 사용(Maven)

<dependency>
    <groupId>org.jobrunr</groupId>
    <artifactId>jobrunr-spring-boot-starter</artifactId>
    <version>3.1.2</version>
</dependency>

설정

Spring의 application.properties에서 아래 두 항목에 대한 설정해 해주면 SPring 에서 초기화 작업을 해준다.

org.jobrunr.background-job-server.enabled=true
org.jobrunr.dashboard.enabled=true

만약 여러개의 Runner를 사용할 예정이면 RDB, No-SQL 혹은 queue를 사용하면 된다.→ 참고

@Bean
public BackgroundJobServer backgroundJobServer(StorageProvider storageProvider, JobActivator jobActivator) {
    final BackgroundJobServer backgroundJobServer = new BackgroundJobServer(storageProvider, jobActivator);
    backgroundJobServer.start();
    return backgroundJobServer;
}

@Bean
public JobActivator jobActivator(ApplicationContext applicationContext) {
    return applicationContext::getBean;
}

@Bean
public JobScheduler jobScheduler(StorageProvider storageProvider) {
    return new JobScheduler(storageProvider);
}

@Bean
public StorageProvider storageProvider(JobMapper jobMapper) {
    //다른 종류의  datasource도 연결 가능함.
    final SQLiteDataSource dataSource = new SQLiteDataSource();
    dataSource.setUrl("jdbc:sqlite:jobrunr.db"));
    final SqLiteStorageProvider sqLiteStorageProvider = new SqLiteStorageProvider(dataSource);
    sqLiteStorageProvider.setJobMapper(jobMapper);
    return sqLiteStorageProvider;
}

Job 정의하기

public class ProductInfoService {

    @Autowired
    private ProductInfoRepository productInfoRepository;

    public void createProductInfo(final ProductInfo productInfo){
        productInfoRepository.save(productInfo);
    }

    @Job(name = "The sample job with variable %0", retries = 2)
    public void executeMakeReportWithProductInfomation(String variable) {
    ...
    }
}

2번 재시도하는 백그라운드 Job을 정의

Job 호출

@Inject
private JobScheduler jobScheduler;

@Inject
private ProductInfoService productInfoService;
//호출 후 잊기
jobScheduler.enqueue(() -> productInfoService.executeMakeReportWithProductInfomation("some string"));
//작업 예약
jobScheduler.schedule(LocalDateTime.now().plusHours(5), () -> productInfoService.executeMakeReportWithProductInfomation("some string"));
//반복 작업 예약
jobScheduler.scheduleRecurrently(Cron.hourly(), () -> productInfoService.executeMakeReportWithProductInfomation("some string"));

'Spring boot' 카테고리의 다른 글

[Spring] Cache  (0) 2022.01.03
[Spring] Maven Wrapper  (0) 2022.01.03
[Spring] EJB, POJO 그리고 Spring  (0) 2021.12.12
[Spring] Kotllin + Spring boot 시작하기  (0) 2021.12.08
[Spring] Transaction 정리  (0) 2021.11.24