本文实例讲述了php基于 swoole 实现的异步处理任务功能。分享给大家供大家参考,具体如下:
安装swoole:
下载官方swoole压缩包,解压进入目录
1
2
3
4
|
$ cd swoole # 进入 swoole 目录 $ phpize $ . /configure --with-php-config= /usr/local/php/bin/php-config #注意查看服务器上是否有这个路径 $ make && make install |
修改php.in文件
1
|
vi /usr/local/php/lib/php .ini |
增加如下内容
1
|
extension = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20160303/swoole.so" // 版本不同路径可能不同 |
保存后重启php-fpm
1
|
$ /etc/init .d /php-fpm restart |
php -m 命令查看是否添加成功 成功则会看到有swoole模块
1
|
$ php -m |
服务端作为守护进程监控任务,新建server.php:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?php $serv = new Swoole\Server( "127.0.0.1" , 9502); $serv ->set( array ( 'task_worker_num' => 4)); $serv ->on( 'Receive' , function ( $serv , $fd , $from_id , $data ) { $task_id = $serv ->task( "Async" ); echo "Dispath AsyncTask: id=$task_id\n" ; }); $serv ->on( 'Task' , function ( $serv , $task_id , $from_id , $data ) { echo "New AsyncTask[id=$task_id]" .PHP_EOL; $serv ->finish( "$data -> OK" ); }); $serv ->on( 'Finish' , function ( $serv , $task_id , $data ) { echo "AsyncTask[$task_id] Finish: $data" .PHP_EOL; }); $serv ->start(); |
用命令行模式打开
1
|
php server.php |
新建一个client.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?php $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); $client ->on( "connect" , function (swoole_client $cli ) { $cli ->send( "GET / HTTP/1.1\r\n\r\n" ); }); $client ->on( "receive" , function (swoole_client $cli , $data ){ echo "Receive: $data" ; $cli ->send( str_repeat ( 'A' , 100). "\n" ); sleep(1); }); $client ->on( "error" , function (swoole_client $cli ){ echo "error\n" ; }); $client ->on( "close" , function (swoole_client $cli ){ echo "Connection close\n" ; }); $client ->connect( '127.0.0.1' , 9502); |
打开一个新的窗口命令行执行
1
|
php client.php |
执行完后会发现在server.php的窗口就会有信息输出
希望本文所述对大家PHP程序设计有所帮助。
原文链接:https://blog.csdn.net/fangdong88/article/details/78050321