我正在尝试使用Spring批处理和spring集成在SFTP服务器上传多个文件。为此,我使用ThreadPoolTaskExecutor进行并行处理。
在每个进程中执行文件上传 但即使所有文件都在SFTP服务器上成功上传,仍然没有停止进程,程序始终保持运行状态。
即使我覆盖JobExecutionListener
@Bean
public JobExecutionListener jobExecutionListener(ThreadPoolTaskExecutor executor) {
return new JobExecutionListener() {
private ThreadPoolTaskExecutor taskExecutor = executor;
@Override
public void beforeJob(JobExecution jobExecution) {
}
@Override
public void afterJob(JobExecution jobExecution) {
taskExecutor.shutdown();
}
};
}
@Bean
public ThreadPoolTaskExecutor threadPoolTaskExecutor()
{
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.initialize();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(10);
executor.setThreadNamePrefix("quantum-runtime-worker-thread");
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
@Bean
public Step uploadFiles()
{
return stepBuilderFactory.get(UPLOAD_FILE_STEP_NAME).tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception
{
log.info("Upload tasklet start executing..");
resources = resourcePatternResolver.getResources(inputFilesPath);
for (Resource anInputResource : resources)
{
log.info("Incoming file <{}> to upload....", anInputResource.getFilename());
threadPoolTaskExecutor().execute(new Runnable() {
@Override
public void run()
{
File zippedFile = null;
try
{
log.info("Uploading file : {}", anInputResource.getFilename());
gateway.upload(zippedFile);
log.info("{} file uploaded : {}", anInputResource.getFilename(), zippedFile.delete());
}
catch (Exception e)
{
log.error("Error occured while uploading a file : {} and the exception is {}",
anInputResource.getFilename(), e);
}
}
});
}
System.out.println("=============POINTER NOT COMMING HERE================");
return RepeatStatus.FINISHED;
}
}).build();
}
@Bean
@ServiceActivator(inputChannel = SFTP_CHANNEL_NAME)
public MessageHandler handler()
{
SftpMessageHandler handler = new SftpMessageHandler(sftpSessionFactory());
handler.setRemoteDirectoryExpression(new LiteralExpression("/"));
handler.setFileNameGenerator(new FileNameGenerator() {
@Override
public String generateFileName(Message<?> message)
{
if (message.getPayload() instanceof File)
{
return ((File) message.getPayload()).getName();
}
else
{
throw new IllegalArgumentException("File expected as payload.");
}
}
});
return handler;
}
@MessagingGateway
@Component
public interface UploadGateway {
@Gateway(requestChannel = SFTP_CHANNEL_NAME)
void upload(File file);
}
答案 0 :(得分:0)
现在我关闭了上下文并成功停止了程序。
ConfigurableApplicationContext context = new SpringApplicationBuilder(QuantumFileUploadApplication.class).web(false).run(args);
context.close();// it works