您好,欢迎访问一九零五行业门户网

PHP swoole怎么用

项目中使用的php,但由于长耗时的任务,前端提交以后,需要服务端异步响应。
服务器异步有多种方案,包括mq,fsocket,swoole等。         (推荐学习: swoole视频教程)
swoole 使用纯 c 语言编写,提供了 php 语言的异步多线程服务器,异步 tcp/udp 网络客户端,异步 mysql,异步 redis,数据库连接池,asynctask,消息队列,毫秒定时器,异步文件读写,异步dns查询。 swoole内置了http/websocket服务器端/客户端、http2.0服务器端。
最重要的是,完美支持php语言。于是使用swoole搭建了一个异步服务器,提供异步响应,推送,定时任务等一系列工作。
swoole是c语言编写,采用编译安装的方式。
安装依赖项有:
php-5.3.10 或更高版本gcc-4.4 或更高版本
makeautoconfpcre (centos系统可以执行命令:yum install pcre-devel)
安装方式:
phpize #如果命令不存在 请在前面加上php的实际路径./configuremake sudo make install
编译完成以后,需要在php.ini中添加扩展
extension=swoole.so
服务端
class server{ private $serv; public function __construct() { $this->serv = new swoole_server("0.0.0.0", 9501); $this->serv->set(array( //'worker_num' => 1, //一般设置为服务器cpu数的1-4倍 'daemonize' => 1, //以守护进程执行 'max_request' => 10000, 'task_worker_num' => 1, //task进程的数量 "task_ipc_mode " => 3 , //使用消息队列通信,并设置为争抢模式 'open_length_check' => true, 'dispatch_mode' => 1, 'package_length_type' => 'n', //这个很关键,定位包头的 'package_length_offset' => 0, //第n个字节是包长度的值 'package_body_offset' => 4, //第几个字节开始计算长度 'package_max_length' => 2000000, //协议最大长度 "log_file" => "/tmp/swoole_test.log" //日志 )); $this->serv->on('receive', array($this, 'onreceive')); $this->serv->on('task', array($this, 'ontask')); $this->serv->on('finish', array($this, 'onfinish')); $this->serv->start(); } public function onreceive( swoole_server $serv, $fd, $from_id, $data ) { //放入任务队列,开始执行 $task_id = $serv->task( $data ); } public function ontask($serv,$task_id,$from_id, $data) { //做一些事情 }
客户端
class client{ private $client, $ip, $port, $params; public function __construct($ip, $port, $params) { $this->ip = $ip; $this->port = $port; $this->params = $params; $this->client = new swoole_client(swoole_sock_tcp, swoole_sock_async); $this->client->set(array( 'open_length_check' => true, 'package_length_type' => 'n', 'package_length_offset' => 0, //第n个字节是包长度的值 'package_body_offset' => 4, //第几个字节开始计算长度 'package_max_length' => 2000000, //协议最大长度 )); //设置事件回调函数 $this->client->on('connect', array($this, 'onconnect')); $this->client->on('receive', array($this, 'onreceive')); $this->client->on('close', array($this, 'onclose')); $this->client->on('error', array($this, 'onerror')); //发起网络连接 $this->client->connect($ip, $port, 3); } public function onreceive( $cli, $data ) { echo "received: " . $data . "\n"; } public function onconnect($cli) { $data = pack('n', strlen($data)) . $data; $cli->send($data); $cli->close(); } public function onclose( $cli) { echo "connection close\n"; } public function onerror() { echo "connect failed\n"; }}
以上就是php swoole怎么用的详细内容。
其它类似信息

推荐信息