第一部分 异步读取文件
异步io的读取有文件大小的限制,最大只支持4Mb,如果大于4Mb可以使用swoole_async_read来实现,这个函数本质是分段读取的。
主要实现的函数有:
- swoole_async_read() 异步读文件,传入路径及回调函数,使用此函数读取文件是非阻塞的,当读操作完成时会自动回调指定的函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php /** * Created by bingxiong. * Date: 4/17/18 * Time: 3:59 AM * Description: */ $result = swoole_async_readfile(__DIR__."/1.txt",function ($filename, $fileContent){ echo "filename:".$filename.PHP_EOL;//PHP_EOL匹配不同操作系统的换行符 \n \r echo "content:".$fileContent.PHP_EOL; }); var_dump($result); echo "start".PHP_EOL; |
实现效果:
注意输出的顺序,bool(true)代表了应读取到文件了,但是这个时候并没有在第一个时间输出,而是继续执行下面的逻辑输出start后,才会输出文件的内容。
第二部分 异步写入文件
- 异步写入文件主要使用swoole_async_writefile(),需要传递介个参数:文件地址、写入内容、回调函数
- swoole_async_writefile()有文件大小限制,超过4MB需要使用swoole_async_write()
- 默认每次写入会覆盖之前的,如果以追加的形式需要添加参数FILE_APPEND
- 可以把交易等重要信息放在日志里,以方便后续的跟进
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php /** * Created by bingxiong. * Date: 4/17/18 * Time: 4:00 PM * Description: */ $content = date("Ymd H:i:s").PHP_EOL; swoole_async_writefile(__DIR__."/1.log",$content,function ($filename){ // todo echo "success".PHP_EOL; },FILE_APPEND); // FILE_APPEND 以追加的方式去写入,没有这个参数每次回覆盖之前的。 // 也有大小限制,超过4MB使用swoole_async_write echo "start".PHP_EOL; |
效果:
接下来实现一个Nginx服务器日志,有请求把请求的时间和内容放在文件中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php /** * Created by bingxiong. * Date: 4/15/18 * Time: 4:16 PM * Description: */ $http = new swoole_http_server("0.0.0.0",8811); $http->set([ 'enable_static_handler' => true, // 'document_root' => "/Users/bingxiong/swoole/hdtocs/demo/data" // 设置静态资源默认存放路径 ]); $http->on('request',function ($request,$response){ // 一旦有请求把请求写入日志当中,非常类似Nginx的日志 $content =[ 'date' => date("Ymd H:i:s"), 'get' => $request->get, 'post' => $request->post, 'header' => $request->post, ]; swoole_async_writefile(__DIR__."/access.log",json_encode($content).PHP_EOL, function ($filename){ // todo },FILE_APPEND); $response->cookie("bing","xxx",time()+1800); $response->end("sss".json_encode($request->get)); }); $http->start(); |
效果:
- 这里使用tail -f filename,这个命令可以实时的查看文件内容