多线程 Spring-boot 控制器方法 [英] Multithread Spring-boot controller method

查看:92
本文介绍了多线程 Spring-boot 控制器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的应用程序 (spring-boot) 运行非常慢,因为它使用 Selenium 来抓取数据、处理数据并显示在主页中.我遇到了多线程,我认为它可以对我的应用程序有用以使其运行得更快,但是教程似乎显示在带有 main.js 的普通 java 应用程序的设置中.如何在我的控制器中多线程处理这个单一方法?

So my application (spring-boot) runs really slow as it uses Selenium to scrape data, processes it and displays in the home page. 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. How can I multithread this single method in my controller?

get.. 方法都是 selenium 方法.我希望同时运行这 4 行代码

The methods get.. are all selenium methods. I'm looking to run these 4 lines of code simultaneously

   @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 的每个请求,都会创建一个新线程,因此您想要实现的目标已经存在.请看:

For every request to RequestMapping, a new thread will be created so what you want to achieve is already there. Please have a look:

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.

更多信息和指南:

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

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

这篇关于多线程 Spring-boot 控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆