我可以将实体传递给一个批次并在作业中使用它吗?

huangapple go评论56阅读模式
英文:

Can I pass an entity to a batch and use it in a job?

问题

以下是翻译好的代码部分:

我有如下批处理作业代码

    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 { "测试作业" } // 我想要输出用户ID
                RepeatStatus.FINISHED
            }
        }
    }

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

    @Scheduled(cron = "30 * * * * *")
    fun batchGo(){
        val user = userRepository.findByIdOrNull(1) ?: throw Exception("未找到用户")

        val jobParameters = JobParametersBuilder()
            .toJobParameters()

        val jobExecution: JobExecution = jobLauncher.run(batchConfig.myJob(),jobParameters)
        if (jobExecution.status == BatchStatus.COMPLETED) {
            println("批处理成功")
        } else {
            println("否")
        }
    }

因此在从数据库中获取用户后我们将其传递给批处理运行我希望在myTask()日志部分中打印传递给它的用户的ID您能给我一些建议吗

请注意,我已经将代码中的HTML实体编码(如")还原为正常的引号和字符,以使代码更易于阅读。

英文:

I have batch job code as below

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
}
}
}

Use a schedule to run a batch every time at a set time,
How to load a specific user from the database when running the batch and send this data to the job and use this user in the job?

@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")
}
}

As a result, after pulling the user out of the database, we pass it to the batch run,
I want to print the ID of the user passed to myTask() log part, can you give me some advice?

答案1

得分: 1

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

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

然后通过StepContribution#getStepExecution#getJobParametersChunkContext#getStepContext#getJobParameters在tasklet中获取它。

@Bean
@StepScope
fun myTask(): Tasklet {
   return Tasklet { contribution, chunkContext ->
            val userId = contribution.stepExecution.jobParameters.getString("userId")
            log.info { " test job $userId" } // 我想要输出用户ID
            RepeatStatus.FINISHED
   }
}
英文:

You can pass the user ID as a job parameter:

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

and get it in the tasklet through the StepContribution#getStepExecution#getJobParameters or ChunkContext#getStepContext#getJobParameters.

@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
}
}

huangapple
  • 本文由 发表于 2023年6月1日 12:55:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76378765.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定