拉拉维尔中的多线程


Multi-Threading in Laravel

我遇到了一个问题,我的数据库调用显着减慢了页面加载速度。我正在从选举数据填充多个图表,我的表包含大约 100 万行,我必须在 getCharts() 方法中的每个方法中多次查询此数据。

我正在使用它将返回数据传递给 JavaScript。

当您单击数据点时,这些图表将重新填充。因此,如果您单击一个点,即('民主),它将重新加载页面并再次调用这些方法。

我要问的是,是否可以在本机 PHP 中做这样的事情。服务器在 linode 上运行 PHP 5.2。

foreach(function in getChartsMethod){
     Start a child thread to process the function. 
}  
join the threads. 
reload the page. 

public function getCharts(){
        $this->get_cast_chart();
        $this->get_party_chart();
        $this->get_gender_chart();
        $this->get_age_chart();
        $this->get_race_chart();
        $this->get_ballot_chart();
        $this->get_county_chart();
        $this->get_precinct_chart();
        $this->get_congressional_district_chart();
        $this->get_senate_district_chart();
        $this->get_house_district_chart();
        return view('elections.index');
    }

示例方法

public function get_party_chart(){
        $query = DB::table($this->tableName)
            ->select('party', DB::raw('count(*) as numVotes'))
            ->groupBy('party')
            ->orderBy('numVotes', 'ASC');
        if ($this->filterParameters != null){
            $query = $query->where(key($this->filterParameters), $this->operator, current($this->filterParameters));
        }
        $chartData = $query->get();
        $chartData = $this->prepare_data_for_chart($chartData, 'party', 'numVotes');
        JavaScript::put(['partyChart' => $chartData]);
    }

多线程在PHP中是可能的,这在Stackoverflow上已经讨论过:如何在PHP应用程序中使用多线程

但是我不知道多线程在这里会对您有多大帮助。我们在谈论多少数据,您在图表中寻找什么样的准确性?显示多少个图表?很多解决方案将来自上下文。

如果是我,我会有一个后台时间表,将"大量"数据预处理成前端更有用/更有用的东西。同样有用/可用完全取决于上下文。当有实际的页面请求时,您只需要传递处理后的数据,而不是实际的"实时"数据。

同样,这将完全取决于应用程序的上下文。也许你需要按分钟的数据,也许你不需要。

Chris 是对的 - 这完全取决于您的应用程序,但如果您到了应用程序无法使用的地步,您应该考虑在 Redis 或 memcached 中兑现您的结果。