问题描述
是它们的任何方式,这样我就可以利用多线程概念并行调用执行,并加快创建的@RestController
的执行速度,该@RestController
将接受String
和List<MultipartFile>
作为请求参数,并且代码为工作正常.问题是如果我通过for循环解析另一个文件.执行所花费的时间更多.
Is their any way so that i can make use of Multithreading concept to call the execution in parallel and make execution faster for created @RestController
which will accepts a String
and List<MultipartFile>
as request parameters, and the code is working fine.Problem here is if i'm parsing one file after other via a for loop. Time taken for execution is more.
@RequestMapping(value = "/csvUpload", method = RequestMethod.POST)
public List<String> csvUpload(@RequestParam String parentPkId, @RequestParam List<MultipartFile> file)
throws IOException {
log.info("Entered method csvUpload() of DaoController.class");
List<String> response = new ArrayList<String>();
String temp = parentPkId.replaceAll("[-+.^:,]", "");
for (MultipartFile f : file) {
String resp = uploadService.csvUpload(temp, f);
response.add(resp);
}
return response;
}
从控制器
,我正在调用uploadService.csvUpload()
方法,其中我正在使用For循环,一个接一个地解析文件.
from controller, i'm calling uploadService.csvUpload()
method where i'm parsing the files one after the other as i'm using For loop.
下面是我的UploadService类
public String csvUpload(String parentPkId, MultipartFile file) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()));
String line = "";
int header = 0;
while ((line = br.readLine()) != null) {
// TO SKIP HEADER
if(header == 0) {
header++;
continue;
}
header++;
//Use Comma As Separator
String[] csvDataSet = line.split(",");
//Saving it to DB
}catch(IOException ex) {
ex.printStackTrace();
}
return "Successfully Uploaded "+ file.getOriginalFilename();
}
欢迎任何线索和建议,谢谢.
any leads and suggestion are welcomed, thanks in advance.
推荐答案
您需要创建一个Class,该类将实现如下所示的callable并将期货存储在列表中,最后按以下方式处理期货
you need to create a Class which will implement callable as below and store futures in a list and finally process the futures as below
public class ProcessMutlipartFile implements Callable<String>
{
private Mutlipartfile file;
private String temp;
private UploadService uploadService;
public ProcessMutlipartFile(Mutlipartfile file,String temp, UploadService uploadService )
{
this.file=file;
this.temp=temp,
this.uploadService=uploadService;
}
public String call() throws Exception
{
return uploadService.csvUpload(temp, file);
}
}
在您的控制器中创建将来的对象列表
in your controller create a list of future object
ExecutorService executor = Executors.newFixedThreadPool(10)
List< Future<String> > futureList = new ArrayList<Future<String>>();
.
.
.
for (MultipartFile f : file) {
futureList.add(executor.submit(new ProcessMutlipartFile(file ,temp,uploadService));
}
最终在您的控制器中
for (Future f :futureList)
{
response.add(f.get());
}
//shuttingdown the Executor
executor.shutdown();
希望这会有所帮助
这篇关于带有多线程的REST Api用于在Spring Boot中处理文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!