官方文档: https://wiki.swoole.com/wiki/page/p-async.html
异步IO,文件操作
swoole_async_readfile($filename, $callback)
异步读取文件
-
$filename
文件名 -
$callback
回调函数,有两个参数function($filename,$content){}
-
$content
文件的内容文件不存在会返回
false
成功打开文件返回true
成功读取文件内容,会调用指定的回调函数callback
注意: swoole_async_readfile
最多读取4M的文件,如果需要的读取文件过大请使用swoole_async_read
函数
代码:
<?php
$res = swoole_async_readfile(__DIR__ . "/1.txt",function ($filename , $content){
echo $filename.PHP_EOL;
echo $content.PHP_EOL;
});
var_dump($res);
echo "start".PHP_EOL;
运行以上代码,会发现.我们是先打印
$res
的值,再打印start
,最后才打印$filename
和$content
并不是我们之前所认为的,代码从上至下执行.
这种特点在所有的异步操作中都有.
swoole_async_writefile($filename,$filecontent,$callback,$flags)
异步写入文件
-
$filecontent
需要写入文件的内容 -
$callback
回调函数function($filename)
-
$flags
写入的选项,默认$filecontent
会覆盖文件内容,与PHP中的file_put_contens
一样. 如果需要追加的话,传入FILE_APPEND
常量代码:
<?php
swoole_async_writefile(__DIR__ . "/1.txt","xixi",function ($filename){
swoole_async_readfile($filename,function ($filename,$content){
echo $content.PHP_EOL;
});
},FILE_APPEND);
如果我们不想让新的内容覆盖掉文件原有的信息,我们就需要添加第四个参数
FILE_APPEND
否则可以不填写
基于HTTP服务的一个编写日志的demo :
<?php
$http = new swoole_http_server('0.0.0.0',8811);
$http->set([
'enable_static_handler' => true,
'document_root' => '/marun'
]);
$http->on('request',function ($request,$response){
$content = [
'date: ' => date("Y-m-d H:i:s",time()),
"get: " => $request->get,
"post: " => $request->post,
"header: " => $request->header
];
//根据日期来生成一个日志文件,一行一条记录.
swoole_async_writefile(__DIR__ . "/" .date("Y-m-d",time()).".log",json_encode($content).PHP_EOL,function ($filename){
echo "write ok".PHP_EOL;
},FILE_APPEND);
$response->end(json_encode($request->get));
});
$http->start();
注意: 如果写入的文件内容过大,可以使用
swoole_async_write
函数
swoole_async_read($filename,$callback,$size,$offset)
异步读文件
此函数与
swoole_async_readfile
不同的是,这个函数是分段来读取文件内容,可以读取超大内容的文件,每次只读取$size
个字节的内容,不会占用太大的内存
$filename
文件名
$callback
回调函数function($filename,$content)
$content
分段读取到的内容 , 如果为空 就说明文件读取完毕return
在回调函数内 可以通过return false
或者return true
来控制是否服务下一段内容,true
继续,false
暂停
$size
分段读取的字节大小 , 每一次 读取的字节大小
$offest
偏移量. 从第几个字节开始读取. 比如 0
从头开始. 1
从第二个开始读取
example:
//每一次读取两个字节的内容, 从第三个开始
swoole_async_read(__DIR__."/1.txt",function ($filename,$content){
echo $content.PHP_EOL;
},1,1);
注意 截取中文乱码.
swoole_async_write($filename, $content, $offset, $callback)
异步写文件
与
swoole_async_writefile
不同,swoole_async_write
是分段写的。不需要一次性将要写的内容放到内存里,所以只占用少量内存。swoole_async_write
通过传入的offset
参数来确定写入的位置。
- 当
offset
的值为-1
的时候,表示内容写入到文件末尾
exmaple:
swoole_async_write(__DIR__."/1.txt","marun".PHP_EOL,-1,function ($filename){
swoole_async_readfile($filename,function ($filename,$content){
echo $content.PHP_EOL;
});
});