Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launching Spring batch job

I have a problem where in I need to receive a series of messages from an MQ queue and write this to a file and initiate a spring batch job with the file as input. Right now I'm thinking of launching the job with wired @Autowired JobLauncher jobLauncher and @Autowired Job job; from the MDB itself.But I feel this is not a good approach as spring batch may create a series of threads and EJB as such doesnt support multi threading.

Is there any other effective way to do this ? I dont want to use quartz scheduler or anything else since it adds complexity. Is there any interface in spring batch itself which launches a job soon after a file comes in a directory ? Any leads in doing this better would be appreciated.

Thanks.

like image 786
nobody Avatar asked Jan 16 '26 22:01

nobody


1 Answers

  • I have a problem where in I need to receive a series of messages from an MQ queue and write this to a file and initiate a spring batch job with the file as input

One way to do that would be engage a bit of Spring Integration, where you would have a file poller, that would poll for a new file:

<file:inbound-channel-adapter id="filePoller"
                              channel="filesAreComing" 
                              directory="file:${input.directory}"
                              filename-pattern="test*" />

Adapt a file message ( java.io.File ) to a file name ( String ), since that is what Spring Batch needs. This can be done with a JobLauncher adapter, that is already available from Spring Batch Admin here:

@ServiceActivator
public JobLaunchRequest adapt(File file) throws NoSuchJobException {

    JobParameters jobParameters = new JobParametersBuilder().addString(
            "input.file", file.getAbsolutePath()).toJobParameters();

    return new JobLaunchRequest(job, jobParameters);
}

wrap it to a JobLaunchRequest ( which is just a holder for a Job and JobParameters ) and send this request [as a message] to JobLaunchingMessageHandler:

<service-activator input-channel="jobLauncher">
    <beans:bean class="org.springframework.batch.integration.launch.JobLaunchingMessageHandler">
        <beans:constructor-arg ref="jobLauncher" />
    </beans:bean>
</service-activator>

that would launch the job.

"input.file" is a parameter that is bound at runtime ( hence #{...} ):

<bean id="reader" class="org.springframework.batch.item.file.FlatFileItemReader" scope="step">
    <property name="resource" value="#{jobParameters[input.file]}" />
    ... line mapper and other props
</bean>
like image 118
tolitius Avatar answered Jan 19 '26 15:01

tolitius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!