首页 > 解决方案 > 多线程 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";
    }

标签: javaspringmultithreadingspring-bootthreadpool

解决方案


对于 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
    }
}

这将为您创建线程池,您可以将其与您的任务一起提供。

更多信息和指南:

https://spring.io/guides/gs/async-method/

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/task/TaskExecutor.html


推荐阅读