rryqszq4 / ngx-php

ngx-php - Embedded php7 or php8 scripting language for nginx module. Mainline development version of the ngx-php.
BSD 2-Clause "Simplified" License
584 stars 56 forks source link

How to connect to mysql async in worker_init ? #80

Open joanhey opened 4 years ago

joanhey commented 4 years ago

I am trying that:

<?php
//app_async.php called from init_worker_by_php
require_once '/ngx_php7/t/lib/mysql.php';

define('DB_HOST', gethostbyname('tfb-database'));
define('DB_PORT', '3306');
define('DB_USER', 'benchmarkdbuser');
define('DB_PASS', 'benchmarkdbpass');
define('DB_NAME', 'hello_world');

$my = new php\ngx\mysql();
yield from $my->connect(DB_HOST, DB_PORT, DB_USER, DB_PASS, DB_NAME);

function db()
{
    ngx_header_set('Content-Type', 'application/json');

    global $my;

    echo json_encode(
        (yield from $my->query('SELECT id,randomNumber FROM World WHERE id = '.mt_rand(1, 10000)))[0]
    );

}

And get this error:

php-ngx-async: 2019/11/04 13:50:35 [error] 9#0: *1 Fatal error: Uncaught Error: Call to undefined function db() in ngx_php eval code:2
php-ngx-async: Stack trace:
php-ngx-async: #0 [internal function]: ngx_content_50c025ec7080d0b5458512d034e7a3bb()
php-ngx-async: #1 [internal function]: Generator->valid()
php-ngx-async: #2 {main}
php-ngx-async:   thrown in ngx_php eval code on line 2, client: 172.18.0.5, server: , request: "GET /db HTTP/1.1", host: "tfb-server:8080"
php-ngx-async: 2019/11/04 13:50:35 [error] 9#0: *1 ngx_php ctx is nil at content inline handler. while keepalive, client: 172.18.0.5, server: 0.0.0.0:8080
rryqszq4 commented 4 years ago

@joanhey This is because app_async.php reports an error in the init_worker_by_php phase, causing the db function to not parse normally. Currently, the init_worker_by_php phase cannot use asynchronous interfaces.

rryqszq4 commented 4 years ago

In init_worker_by_php phase can not output error log, and need to fix~

joanhey commented 4 years ago

The important think is to have async queries. The connection in most cases don't need to be async, but better if it is also posible to use in some cases.