Spring Boot 我可以将实体传递给批处理并在作业中使用它吗?

uqdfh47h  于 2023-06-05  发布在  Spring
关注(0)|答案(1)|浏览(166)

我有批作业代码如下

import kr.test.testApp.core.domain.user.UserRepository
import mu.KotlinLogging
import org.springframework.batch.core.Job
import org.springframework.batch.core.Step
import org.springframework.batch.core.configuration.annotation.StepScope
import org.springframework.batch.core.job.builder.JobBuilder
import org.springframework.batch.core.repository.JobRepository
import org.springframework.batch.core.step.builder.StepBuilder
import org.springframework.batch.core.step.tasklet.Tasklet
import org.springframework.batch.repeat.RepeatStatus
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.transaction.PlatformTransactionManager

private val log = KotlinLogging.logger {  }

@Configuration
class BatchConfig(
    val jobRepository: JobRepository,
    val transactionManager: PlatformTransactionManager,
    val userRepository: UserRepository,
){
    @Bean
    fun myJob(): Job {
        return JobBuilder("taskletJob", jobRepository)
            .start(myStep())
            .build()
    }

    @Bean
    fun myStep(): Step {
        return StepBuilder("taskletStep", jobRepository)
            .allowStartIfComplete(true)
            .tasklet(myTask(), transactionManager)
            .build()
    }

    @Bean
    @StepScope
    fun myTask(): Tasklet {
        return Tasklet { _, _ ->
            log.info { " test job " } // i want output userid
            RepeatStatus.FINISHED
        }
    }
}

使用计划每次在设定的时间运行批处理,如何在运行批处理时从数据库加载特定用户,并将此数据发送到作业,并在作业中使用此用户?

@Scheduled(cron = "30 * * * * *")
fun batchGo(){
    val user = userRepository.findByIdOrNull(1) ?: throw Exception("user not found")

    val jobParameters = JobParametersBuilder()
        .toJobParameters()

    val jobExecution: JobExecution = jobLauncher.run(batchConfig.myJob(),jobParameters)
    if (jobExecution.status == BatchStatus.COMPLETED) {
        println("batch success")
    } else {
        println("no")
    }
}

结果把用户从数据库中拉出来之后,我们把它传递给批处理运行,我想打印传递给myTask()log部分的用户的ID,你能给予我一些建议吗?

wfveoks0

wfveoks01#

可以将用户ID作为作业参数传递:

String userId = ...
val jobParameters = JobParametersBuilder()
        .addString("userId", userId)
        .toJobParameters()

并通过StepContribution#getStepExecution#getJobParametersChunkContext#getStepContext#getJobParameters将其放入tasklet中。

@Bean
@StepScope
fun myTask(): Tasklet {
   return Tasklet { (contribution, chunkContext) ->
            String userId = contribution.getStepExecution().getJobParameters().getString("userId");
            log.info { " test job " } // i want output userid
            RepeatStatus.FINISHED
   }
}

相关问题