美文网首页
thinkphp5.1 workerman核心修改攻略

thinkphp5.1 workerman核心修改攻略

作者: 张大胆_6a19 | 来源:发表于2019-03-25 18:54 被阅读0次

    1、thinkphp原来的Response设置header方式不管用了,为什么正常开发的时候却又好用?

    \vendor\topthink\think-worker\src\Application.php的worker接管了Response getContent解析,无论\application下如何业务逻辑处理,只要Controller return返回的Response交给worker处理即可,我们打开\vendor\topthink\think-worker\src\Application.php,看到worker方法中通过WorkerHttp对header重新处理,workerman对header只能通过WorkerHttp。

    ```php

    use \Workerman\Connection\AsyncTcpConnection;

    // 与远程连接池服务建立异步链接,ip为远程连接池服务的ip,如果是集群就是lvs的ip

    $sql_connection = new AsyncTcpConnection('Text://ip:1234');

    // 发送sql

    $sql_connection->send("SELECT ... FROM .....");

    // 异步获得sql结果

    $sql_connection->onMessage = function($sql_connection, $sql_result)

    {

        // 这里只是打印结果

        var_dump(json_decode($task_result));

    };

    // 执行异步链接

    $sql_connection->connect();

    ```

    ```

    public function worker($connection)

    {

        try {

            ob_start();

            // 重置应用的开始时间和内存占用

            $this->beginTime = microtime(true);

            $this->beginMem  = memory_get_usage();

            // 销毁当前请求对象实例

            $this->delete('think\Request');

            $pathinfo = ltrim(strpos($_SERVER['REQUEST_URI'], '?') ? strstr($_SERVER['REQUEST_URI'], '?', true) : $_SERVER['REQUEST_URI'], '/');

            $this->request->setPathinfo($pathinfo);

            if ($this->config->get('session.auto_start')) {

                WorkerHttp::sessionStart();

    }

            // 更新请求对象实例

            $this->route->setRequest($this->request);

            $response = $this->run();

            $response->send();

            $content = ob_get_clean();

            // Trace调试注入

            if ($this->env->get('app_trace', $this->config->get('app_trace'))) {

                $this->debug->inject($response, $content);

    }

            $this->httpResponseCode($response->getCode());

            foreach ($response->getHeader() as $name => $val) {

                // 发送头部信息

                WorkerHttp::header($name . (!is_null($val) ? ':' . $val : ''));

    }

            $connection->send($content);

        } catch (HttpException $e) {

            $this->exception($connection, $e);

        } catch (\Exception $e) {

            $this->exception($connection, $e);

        } catch (\Throwable $e) {

            $this->exception($connection, $e);

    }

    }

    ```

    我们按照原来thinkphp开发方式对异常进行拦截

    相关文章

      网友评论

          本文标题:thinkphp5.1 workerman核心修改攻略

          本文链接:https://www.haomeiwen.com/subject/sdgbvqtx.html