swoole 生命周期 如何定义常驻内存的对象

sowork
  • 204
  1. swoole生命周期官方文档 https://wiki.swoole.com/wiki/page/354.html

class Test{

    private $http;

    // 程序全局区变量
    public $param1 = 0;
    // 程序全局区变量
    public $param2 = 0;

    public $param3 = 0;

    public function createTCPServer() {
        $this->http = new Swoole\Server("0.0.0.0", 18306);
        $this->http->set([
            'worker_num' => 2,
        ]);

        $this->http->on('workerStart', function ($server, $worker_id) {
            var_dump("workerStart" . $worker_id);
            ++$this->param2;
        });

        $this->http->on('connect', function ($serv, $fd){
            ++$this->param3;
            var_dump("接受到请求,param3目前值为:" . $this->param3);
        });

        $this->http->on('receive', function (swoole_server $server, int $fd, int $reactor_id, string $data){
            var_dump("param1:" . ++$this->param1);
            var_dump("param2:" . ++$this->param2);
            var_dump("param3:" . $this->param3);
            var_dump($a);
        });

        $this->http->start();
    }

    public function createHttpServer() {
        $this->http = new Swoole\Http\Server("0.0.0.0", 18307);
        $this->http->set([
            'worker_num' => 2,
            'task_worker_num' => 0,
            'max_request' => 50,
            'dispatch_mode' => 1,
        ]);

        $this->http->on('workerStart', function ($server, $worker_id) {
            var_dump("workerStart" . $worker_id);
        });

        $this->http->on('request', function ($request, $response){
            var_dump("param1:" . ++$this->param1);
            var_dump("param2:" . ++$this->param2);
            var_dump("param3:" . $this->param3);
        });

        $this->http->start();
    }
}

(new Test())->createTCPServer();

疑问

  • param1 param2 param3这三个属性应该是 程序全局区对象
  • 如何定义一个 进程全局期对象 ,并且在其他地方访问?
  • 如何定义一个 会话期 对象,比如在onConnect定义,在onReceive访问?
  • 如何定义一个 请求期 对象,比如在onReceive定义,在onClose访问?
回复
阅读 666
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏