请教关于全局数据

fanzhou

有一个较大的数据文件,好几个G(L),是N个为K字节元素的数组(L = N*K)。现在提供一个http的接口,根据id返回第x个元素。
如果nginx+php-fpm,每次都要读文件,很耗时间。所以打算用Workerman来实现。但根据文档尝试都失败了。特来请教,如何使这个数据能够成为全局变量,只load一次。谢谢!

代码如下,客户端每次访问,耗时都几百ms,说明每次都在读文件。

<?php
require_once '/Workerman/Autoloader.php';
use Workerman\Worker;

define('LENGTH_ITEM', 12);

// ## http worker ##
$http_worker = new Worker("http://0.0.0.0:2345");

// 4 processes
$http_worker->count = 4;
$raw_idx = '';
$raw_total = 0;

$http_worker->onWorkerStart = function($http_worker)
{
    global $raw_idx, $raw_total;

    $raw_idx = file_get_contents('idx_cvids');
    $raw_total = intval(strlen($raw_idx) / LENGTH_ITEM);
    var_dump($raw_total);
};

// Emitted when data received
$http_worker->onMessage = function($connection, $data)
{
    global $raw_idx, $raw_total;

    $ts_start = microtime(TRUE);
    if (isset($_GET)) {
        $idx = $_GET;
    }
    else {
        $idx = 0;
    }
    $out = " >> hello world: $idx -- " . strlen($raw_idx) . ' -- ' . bin2hex(substr($raw_idx, $idx * LENGTH_ITEM, LENGTH_ITEM)) . "\n";
    $ts_end = microtime(TRUE);
    $connection->send(($ts_end - $ts_start) . $out);
};

// run all workers
Worker::runAll();
?>
3764 2 0
2个回答

fanzhou

改用对象的static成员就可以了。谢谢作者提供这么好的框架!!!

<?php
class PersistentData
{
    static public $raw_ids = NULL;

    public static function instance()
    {
        if(!self::$raw_ids)
        {
            self::$raw_ids = file_get_contents('idx_cvids');
        }
    }
}

require_once '/home/fanzhou/common/Workerman/Autoloader.php';
use Workerman\Worker;

define('LENGTH_CVID', 12);

#Worker::$stdoutFile = './log';

// ## http worker ##
$http_worker = new Worker("http://0.0.0.0:2345");

// 4 processes
$http_worker->count = 2;
$raw_idx = new PersistentData();
$raw_idx->instance();
$raw_total = intval(strlen($raw_idx::$raw_ids) / LENGTH_CVID);
var_dump($raw_total);

// Emitted when data received
$http_worker->onMessage = function($connection, $data)
{
    global $raw_idx, $raw_total;

    $ts_start = microtime(TRUE);
    if (isset($_GET)) {
        $idx = $_GET;
    }
    else {
        $idx = 0;
    }
    $out = " >> hello world: $idx -- " . strlen($raw_idx::$raw_ids) . ' -- ' . bin2hex(substr($raw_idx::$raw_ids, $idx * LENGTH_CVID, LENGTH_CVID)) . "\n";
    $ts_end = microtime(TRUE);
    $connection->send(($ts_end - $ts_start) . $out);
};

// run all workers
Worker::runAll();
?>
  • 暂无评论
walkor 打赏

对,可以用static

  • 暂无评论
年代过于久远,无法发表回答
×
🔝