swoole初探笔记3异步处理

1、异步读取文件

//面向对象方式
swoole_async_readfile(string $filename,$callback);
//纯函数swoole异步读取文件
Swoole\Async::readFile(string $filename,$callback);

//异步读取
swoole_async_readfile(__DIR__."/1.txt",function($filename,$content){
    echo "$filename $content";
});
2、异步文件写入

swoole_async_writefile($filename,$fileContent,$callback,$flags=0)
$fileContent 写入的内容 最大写入4M
$flags 写入的选项 FILE_APPEND表示追加到文件末尾

$content = 'hello world';
swoole_async_writefile("2.txt",$content,function ($filename){
    echo $filename;
},0);
3、异步事件

swoole_event_add($sock,$read_callback,$write_callback=null,$flags=null);

4、异步mysql

swoole_mysql
connect on escape query

//实例化资源
$db = new swoole_mysql();

$config = [
    'host' => '127.0.0.1',
    'user' => 'root',
    'password' => '!@#yhj123',
    'database' => 'hong',
    'charset'  => 'utf8',
];
//连接数据库
$db->connect($config,function ($db,$r){
    if($r === false){
        var_dump($db->connect_errno,$db->connect_error);
        die("连接失败");
    }
    //成功
    $sql = 'show tables';
    $db->query($sql,function (swoole_mysql $db,$r){
        if($r === false){
            var_dump($db->error);
            die("操作失败");
        }elseif($r === true){
            var_dump($db->affected_rows,$db->insert_id);
        }
        var_dump($r);
        $db->close();
    });
});

你可能感兴趣的:(swoole初探笔记3异步处理)