简体   繁体   中英

Multithread Spring-boot controller method

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?

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";
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM