【问题标题】:Multithread Spring-boot controller method多线程 Spring-boot 控制器方法
【发布时间】:2020-11-06 16:45:39
【问题描述】:

所以我的应用程序(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";
    }

【问题讨论】:

    标签: java spring multithreading spring-boot threadpool


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2015-07-22
      • 1970-01-01
      • 2017-12-10
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      相关资源
      最近更新 更多