直击Thinkphp中的Swoole

1,955 阅读2分钟

ThinkPHP是一个开源的PHP框架,是为了简化企业级应用开发和敏捷WEB应用开发而诞生的。使用面向对象的开发结构和MVC模式,融合了Struts的Action、Dao思想、JSP的TagLib(标签库)、RoR的ORM映射和ActiveRecord模式,封装了CURD和一些常用操作,单一入口模式等,在模版引擎、缓存机制、认证机制和扩展性方面均有独特的表现。

Swoole是php异步、并行、高性能的网络通信引擎,使用纯C语言编写。提供了php语言的异步多线程服务器,异步TCP/UDP网络客户端,异步MySQL,异步Redis,数据库的连接池,AsyncTask,消息队列,毫秒定时器,异步文件读写,异步DNS查询。

swoole.php配置文件,然后设置:

<!--?phpreturn [
    'host'  =--> 'tp5.com',
    'port'  =>   9508,];
可以支持Swoole自身的配置参数设置,例如:
<!--?phpreturn [
    'host'          =--> 'tp5.com',
    'port'          =>   9508,
    'worker_num'    =>   4,
    'max_request'   =>   1000,];

扩展中定义了onWorkerStart和onRequest事件回调方法(如果不熟悉请不要随意替换),如果你需要自定义swoole的事件回调方法,可以在配置文件中使用闭包定义。

<!--?phpreturn [
    'host'          =--> 'tp5.com',
    'port'          =>   9508,
    'worker_num'    =>   4,
    'max_request'   =>   1000,
    'WorkerStop'    =>   function($server, $worker_id){
        // 添加你的代码
    },];

或者直接在配置文件中添加

使用Swoole作为Server服务端

可以支持直接启动一个Swoole server(需要2.0.9+版本)

php think swoole:server

会在0.0.0.0:9508启动一个Websocket服务。

如果需要自定义参数,可以在config/swoole_server.php中进行配置

包括:


并且支持swoole所有的参数。
也支持使用闭包方式定义相关事件回调。

return [
    // 扩展自身配置
    'host'         => '0.0.0.0', // 监听地址
    'port'         => 9501, // 监听端口
    'type'         => 'socket', // 服务类型 支持 socket http server
    'mode'         => SWOOLE_PROCESS,
    'socket_type'  => SWOOLE_SOCK_TCP,

    // 可以支持swoole的所有配置参数
    'daemonize'    => false,

    // 事件回调定义
    'onOpen'       => function ($server, $request) {
        echo "server: handshake success with fd{$request->fd}\n";
    },

    'onMessage'    => function ($server, $frame) {
        echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
        $server->push($frame->fd, "this is server");
    },

    'onRequest'    => function ($request, $response) {
        $response->end("<h1>Hello Swoole. #" . rand(1000, 9999) . "</h1>");
    },

    'onClose'      => function ($ser, $fd) {
        echo "client {$fd} closed\n";
    },];

也可以使用自定义的服务类

<!--?php
namespace app\http;use think\swoole\Server;class Swoole extends Server{
    protected $host = '127.0.0.1';
    protected $port = 9502;
    protected $option = [ 
        'worker_num'=--> 4,
        'daemonize' => true,
        'backlog'   => 128
    ];

    public function onReceive($server, $fd, $from_id, $data)
{
        $server->send($fd, 'Swoole: '.$data);
    }}

支持swoole所有的回调方法定义(回调方法必须是public类型)
serverType 属性定义为 socket或者http
则支持swoole的swoole_websocket_server和swoole_http_server
然后在swoole_server.php中增加配置参数:

return [
    'swoole_class'  =>   'app\http\Swoole',];

定义该参数后,其它配置参数都不再有效。

再命令行启动服务端

php think swoole:server
支持reload|restart|stop|status 操作

php think swoole:server reload