有一個較大的數(shù)據(jù)文件,好幾個G(L),是N個為K字節(jié)元素的數(shù)組(L = N*K)。現(xiàn)在提供一個http的接口,根據(jù)id返回第x個元素。
如果nginx+php-fpm,每次都要讀文件,很耗時間。所以打算用Workerman來實現(xiàn)。但根據(jù)文檔嘗試都失敗了。特來請教,如何使這個數(shù)據(jù)能夠成為全局變量,只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();
?>
改用對象的static成員就可以了。謝謝作者提供這么好的框架?。。?/p>
<?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();
?>