Multithread Spring-boot controller method

让人想犯罪 __ 提交于 2020-07-22 05:18:50

问题


So my application (spring-boot) runs really slow as it uses Selenium to scrap 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?

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

   @Autowired
        private WebScrap webscrap;
    
    @RequestMapping(value = "/")
    public String printTable(ModelMap model) {
        model.addAttribute("alldata", webscrap.getAllData());
        model.addAttribute("worldCases", webscrap.getWorlValues().get(0));
        model.addAttribute("worldDeaths", webscrap.getWorlValues().get(1));
        model.addAttribute("worldPop", webscrap.getWorlValues().get(2));

        return "index";
    }

回答1:


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.

More information and guidelines:

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

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



来源:https://stackoverflow.com/questions/62944457/multithread-spring-boot-controller-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!