🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## Context 该 Context 翻译过来就是上下文管理,与 Golang 的 context 功能完全一致,主要作用有两个: * 控制 goroutine 的取消、超时 * 保存当前请求的上下文数据 框架 HTTP、gRPC、JSON-RPC 的请求参数中都会包含该对象。 ## WithValue 设置、获取值: ~~~ $ctx = new \Mix\Context\Context(); $ctx->withValue('foo', 'bar'); $value = $ctx->value('foo'); ~~~ ## WithCancel 开启一个协程消费 `$c1` 通道的消息,当 `$cancelCtx->cancel()` 调用时取消该操作。 ~~~ $c1 = new \Mix\Context\Context(); $ctx = new \Mix\Context\Context(); $cancelCtx = $ctx->withCancel(); xgo(function () use ($c1, $cancelCtx) { while (true) { if (select( select_case(select_pop($c1), function ($value) { var_dump($value); }), select_case(select_pop($cancelCtx->done()), function ($value) { return SELECT_BREAK; }) )->run()->break()) { return; } } }); $cancelCtx->cancel(); ~~~ ## WithTimeout 开启一个协程消费 `$c1` 通道的消息,当 `$timeoutCtx` 达到超时条件时取消该操作。 ~~~ use Mix\Time\Time; $c1 = new \Mix\Context\Context(); $ctx = new \Mix\Context\Context(); $timeoutCtx = $ctx->withTimeout(3 * Time::SECOND); xgo(function () use ($c1, $timeoutCtx) { while (true) { if (select( select_case(select_pop($c1), function ($value) { var_dump($value); }), select_case(select_pop($timeoutCtx->done()), function ($value) { return SELECT_BREAK; }) )->run()->break()) { return; } } }); ~~~