java - 多线程 Spring-boot 控制器方法
问题描述
所以我的应用程序(spring-boot)运行速度非常慢,因为它使用 Selenium 来抓取数据、处理数据并显示在主页上。我遇到了多线程,我认为它可以让我的应用程序运行得更快,但是这些教程似乎显示在带有 main.java 的普通 java 应用程序的设置中。如何在我的控制器中多线程这个单一方法?
get.. 方法都是 selenium 方法。我希望同时运行这 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";
}
解决方案
对于 RequestMapping 的每个请求,都会创建一个新线程,因此您想要实现的目标已经存在。请看一看:
https://www.oreilly.com/library/view/head-first-servlets/9780596516680/ch04s04.html
如果您出于其他原因仍想使用多线程,您会发现以下内容很有用:
@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
}
}
这将为您创建线程池,您可以将其与您的任务一起提供。
更多信息和指南:
推荐阅读
- php - PHP替换公式中的特定值
- mysql - 如何使用 Linux 和 MariaDB 将数据导入或导出到另一台服务器
- java - 键为空时处理 Firebase 通知远程消息
- codenameone - 如何创建包含 Switch 组件的列表
- php - 在 wordpress 中添加自定义 rest api 支持时要编辑哪个文件
- android - 如何使用 AWS/GCP 在 Android 应用程序上设置直播?
- python - Pandas:根据多列值删除或更改特定行
- azure - 无法为 Azure Nodejs SDK 指定中国区域
- javascript - 在 Jest 测试中设置时刻时区
- json - 类型“数字”不可分配给类型“字符串”。如何将数字转换为字符串