线上有个分词服务,我修改了CutWordsServerEvent 的onMessage方法后,先清理opcache,然后执行reload操作,代码不生效,请教一下各位大佬,怎么解决
class CutWordsServerCommand extends Command
{
protected $signature = 'cut-word-server {action} {--daemon}';
protected $description = '分词服务';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$action = $this->argument('action');
if (!in_array($action, ['start', 'stop', 'reload'])) {
$this->error('参数错误');
exit;
}
if ($this->option('daemon')) {
Worker::$daemonize = true;
}
$httpWorker = new Worker("http://0.0.0.0:8080");
$httpWorker->count = 4;
// 启动时执行的回调函数,这里可以执行一些初始化操作
$httpWorker->onWorkerStart = function (Worker $worker) {
ini_set('memory_limit', '1024M');
Jieba::init(['mode' => 'default', 'dict' => 'big']);
Finalseg::init();
JiebaAnalyse::init();
$memory = getMemory();
$this->info("进程ID" . $worker->id . " 结巴分词加载完毕,当前内存消耗{$memory}");
require_once base_path().'/app/Events/CutWordsServerEvent.php';
$worker->onMessage = [new CutWordsServerEvent(), 'onMessage'];
};
// 运行 Worker,如果你不想在命令行运行,可以注释掉这行
Worker::runAll();
}
}
class CutWordsServerEvent
{
public function onMessage($connection, Request $request)
{
$startTime = microTimeFloat();
$content = trim($request->post('splitContent'));
$topNum = (int)$request->post('topNum', 15);
$response = new Response();
$response->header('Content-Type', 'application/json');
$response->header('Cache-Control', 'no-cache, private');
if (empty($content)) {
$result = makeStdRes(-1, '请求参数错误');
$result['costTime'] = microTimeFloat() - $startTime;
$response->withBody(json_encode($result));
$connection->send($response);
return;
}
$tags = JiebaAnalyse::extractTags($content, $topNum);
$result = makeStdRes(1, '分词请求成功', $tags);
$result['costTime'] = microTimeFloat() - $startTime;
$response->withBody(json_encode($result));
$connection->send($response);
}
}
我是靠注释 $result['costTime'] = microTimeFloat() - $startTime; 请求接口得到的结果有没有costTime 判断代码有没有生效的
文档有说明,写死在start.php 里的代码无法热更新。
把onWorkerStart里的业务代码单独放到一个文件里,然后onMessage的时候加载这个文件。
感谢您的回复,但是我代码是这样的啊,我onMessage的代码都放在 CutWordsServerEvent.php 里了, 是在onWorkerStart 时候用require_once 加载的。这是我的
$httpWorker->onWorkerStart = function (Worker $worker) {
ini_set('memory_limit', '1024M');
Jieba::init(['mode' => 'default', 'dict' => 'big']);
Finalseg::init();
JiebaAnalyse::init();
$memory = getMemory();
$this->info("进程ID" . $worker->id . " 结巴分词加载完毕,当前内存消耗{$memory}");
require_once base_path().'/app/Events/CutWordsServerEvent.php';
$worker->onMessage = [new CutWordsServerEvent(), 'onMessage'];
};
这是官方文档写的:
以下代码reload后会自动更新
$worker = new Worker('http://0.0.0.0:1234');
$worker->onWorkerStart = function($worker) { // onWorkerStart是进程启动后触发的回调
require_once __DIR__ . '/your/path/MessageHandler.php'; // 进程启动后载入的文件支持热更新
$messageHandler = new MessageHandler();
$worker->onMessage = [$messageHandler, 'onMessage'];
};
MessageHandler.php改动后执行 php start.php reload,MessageHandler.php会重新载入内存达到更新业务逻辑的效果。
我没看出来有啥区别啊
意思是onWorkerStart内的所有代码都要放在一个文件里require,你上面的代码有一部分没有在require的文件里?