【发布时间】:2019-03-04 03:46:33
【问题描述】:
我必须上传 CSV,将其转换为 Java 对象,然后保存在数据库中。我正在使用 Spring Boot 和 Spring Batch 来实现这一点。我已经阅读了多个教程。在分析完这些之后,Spring Batch Job 似乎在作业完成之前作为响应发送给客户端异步运行。但是我需要在作业执行完成后向客户端发送响应。有可能吗?请帮助解决此问题。谢谢 我的控制器代码如下:
@RestController
public class AppRestCtrl {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
JobLauncher jobLauncher;
@Autowired
Job job;
@PostMapping("/processFile")
public ResponseEntity convertCsvToObject(@RequestParam("fileData") MultipartFile file) throws Exception {
final Path rootLocation = Paths.get("uploads");
if(!Files.exists(rootLocation)) {
Files.createDirectories(rootLocation);
}
if(file.isEmpty()) {
return ResponseEntity.badRequest().body("Empty File Not Allowed");
}
if(!file.getOriginalFilename().contains(".csv")) {
return ResponseEntity.badRequest().body("File is Invalid!");
}
Files.deleteIfExists(rootLocation.resolve(file.getOriginalFilename()));
Files.copy(file.getInputStream(), rootLocation.resolve(file.getOriginalFilename()));
try {
JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis())
.toJobParameters();
jobLauncher.run(job, jobParameters);
} catch (Exception e) {
logger.info(e.getMessage());
return ResponseEntity.ok("Batch Process Started Successfully!");
}
}
批量配置文件:
@Configuration
public class BatchConfig {
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
@Bean
public Job job() {
return jobBuilderFactory.get("job").incrementer(new RunIdIncrementer()).listener(new Listener())
.flow(step1()).end().build();
}
@Bean
public Step step1() {
return stepBuilderFactory.get("step1").<ObjectNode, JsonNode>chunk(1)
.reader(Reader.reader("uploads\\students.csv"))
.processor(new Processor()).writer(new Writer()).build();
}
}
【问题讨论】:
标签: java spring-boot asynchronous spring-batch batch-processing