这里是我自己整理的一些资料,大家不懂的可以相互学习呀。。。

Swoole Http服务器异步mysql

PHP ZZT 1700次浏览 已收录 0个评论

异步(协程):

<?php

$http = new swoole_http_server("0.0.0.0", 9501);

$http->on('request', function($request, $response){
    $swoole_mysql1 = new Swoole\Coroutine\MySQL();
    $swoole_mysql2 = new Swoole\Coroutine\MySQL();

    $swoole_mysql1->connect([
        'host' => '127.0.0.1',
        'port' => 3306,
        'user' => 'root',
        'password' => 'root',
        'database' => 'swoole',
    ]);
    $swoole_mysql2->connect([
        'host' => '127.0.0.1',
        'port' => 3306,
        'user' => 'root',
        'password' => 'root',
        'database' => 'swoole',
    ]);

    $res1 = $swoole_mysql1->query('SELECT * FROM data1');
    $res2 = $swoole_mysql2->query('SELECT * FROM data2');

    $response->header("Content-Type", "text/html; charset=utf-8");
    $response->end("<h1>Hello Swoole. #".count($res1).count($res2)."</h1>");

});

$http->start();

同步:

<?php

$http = new swoole_http_server("0.0.0.0", 9501);

$http->on('request', function($request, $response){
    $swoole_mysql1 = mysqli_connect('127.0.0.1', 'root', 'root', 'swoole', 3306);
    $swoole_mysql2 = mysqli_connect('127.0.0.1', 'root', 'root', 'swoole', 3306);

    $res1 = $swoole_mysql1->query('SELECT * FROM data1');
    $res2 = $swoole_mysql2->query('SELECT * FROM data2');

    $response->header("Content-Type", "text/html; charset=utf-8");
    $response->end("<h1>Hello Swoole. #".$res1->num_rows.$res2->num_rows."</h1>");

});

$http->start();

但是异步mysql不能再task中执行,因为task中只能执行同步操作,不能执行异步操作。


乐趣公园 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明Swoole Http服务器异步mysql
喜欢 (1)

文章评论已关闭!