Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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

  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 SwooleServer("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 SwooleHttpServer("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访问?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...