【问题标题】:Multihread for requestmapping in spring boot [closed]Spring Boot中请求映射的多线程[关闭]
【发布时间】:2020-11-08 11:44:48
【问题描述】:

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


【解决方案1】:

您可以创建线程并等待它们完成。

@RequestMapping(value = "/")
public String printTable(ModelMap model) {
    // Create a thread and define his operation.
    Thread alldata = new Thread(() -> {
        model.addAttribute("alldata", webscrape.getAllData());
    });
    alldata.start(); // <-- This executes the thread without locking current code.

    // Create a thread and define his operation.
    Thread worldCases = new Thread(() -> {
        model.addAttribute("worldCases", webscrape.getWorlValues().get(0));
    });
    worldCases.start(); // <-- This executes the thread without locking current code.

    // Create a thread and define his operation.
    Thread worldDeaths = new Thread(() -> {
        model.addAttribute("worldDeaths", webscrape.getWorlValues().get(1));
    });
    worldDeaths.start(); // <-- This executes the thread without locking current code.

    // Create a thread and define his operation.
    Thread worldPop = new Thread(() -> {
        model.addAttribute("worldPop", webscrape.getWorlValues().get(2));
    });
    worldPop.start(); // <-- This executes the thread without locking current code.

    // Wait until every thread has finished.
    alldata.join();
    worldCases.join();
    worldDeaths.join();
    worldPop.join();

    return "index";
}

您必须注意ModelMap 变量的线程安全。它们将来自不同的线程,添加属性等。这意味着如果它们没有准备好,它可能会陷入异步异常。

另外,请注意您的休息控制器创建的线程数。作为建议,您可以将此任务委托给其他可以更好地管理线程的组件。

【讨论】:

  • 感谢您的回答。它工作得很好!我有几个问题,希望你不介意回答。 1)异步。因此,只有 worldCases 与它在其方法中调用 worldPop 的其他情况有些相关。你会认为异步和线程安全吗? 2)如果我更多的线程说100,有什么问题?问题仅出在我的计算机硬件上吗?如果是这样,假设硬件较弱,您是否建议分批设置线程?
  • @Fenzox 关于线程数,你可以使用某种类型的池来控制最大同时线程数。例如 Spring 的ThreadPoolTaskExecutor
  • 而且是硬件的限制吧?
  • @Fenzox 关于异步问题,当你打开不同的线程时,它们可以尝试同时访问一些数据。想象一下,您有一个值为1 的整数,并且两个线程试图用+2 更新该值,结果会是什么?那是个问题!您必须管理线程查找/等待或使用准备好的类,如AtomicInteger/ConcurrentHashMap,以避免尝试同时通过两个线程更新数据。
  • @Fenzox 它可能会受到硬件的限制,是的,但问题的原因可能有不同的原因,例如有人出于恶意而多次调用您的 API。
猜你喜欢
  • 2019-11-25
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
  • 2019-02-03
  • 2019-11-13
  • 2020-04-19
  • 2018-03-18
  • 2018-10-02
相关资源
最近更新 更多