[英]Multithread Spring-boot controller method
So my application (spring-boot) runs really slow as it uses Selenium to scrape data, processes it and displays in the home page.所以我的应用程序(spring-boot)运行很慢,因为它使用 Selenium 来抓取数据,处理它并显示在主页上。 I came across multithreading and I think it can be useful to my application to allow it to run faster, however the tutorials seem to display in the setting of a normal java application with a main.
我遇到了多线程,我认为它可以让我的应用程序运行得更快,但是这些教程似乎显示在一个普通的 java 应用程序的设置中。 How can I multithread this single method in my controller?
如何在我的 controller 中多线程这个单一方法?
The methods get.. are all selenium methods. get..的方法都是selenium方法。 I'm looking to run these 4 lines of code simultaneously
我希望同时运行这 4 行代码
@Autowired
private WebScrape webscrape;
@RequestMapping(value = "/")
public String printTable(ModelMap model) {
model.addAttribute("alldata", webscrape.getAllData());
model.addAttribute("worldCases", webscrape.getWorlValues().get(0));
model.addAttribute("worldDeaths", webscrape.getWorlValues().get(1));
model.addAttribute("worldPop", webscrape.getWorlValues().get(2));
return "index";
}
For every request to RequestMapping, a new thread will be created so what you want to achieve is already there.对于 RequestMapping 的每个请求,都会创建一个新线程,因此您想要实现的目标已经存在。 Please have a look:
请看一看:
https://www.oreilly.com/library/view/head-first-servlets/9780596516680/ch04s04.html https://www.oreilly.com/library/view/head-first-servlets/9780596516680/ch04s04.html
If you want to use multithreading anyway for other reason you can find the following useful:如果您出于其他原因仍想使用多线程,您会发现以下内容很有用:
@SpringBootApplication
@EnableAsync
public class ExampleSpringBootApp {
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(5);
executor.setQueueCapacity(25);
return executor;
}
public static void main(String[] args) {
//some code
}
}
This will create for you threadpool which you can feed with your tasks.这将为您创建线程池,您可以将其与您的任务一起提供。
More information and guidelines:更多信息和指南:
https://spring.io/guides/gs/async-method/ https://spring.io/guides/gs/async-method/
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/task/TaskExecutor.html https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/task/TaskExecutor.ZFC35FDC70D5FC69D2693EZ5A
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.