swoft 协程 的使用

控制器访问 /hi

    /**

     * @Swoft\Bean\Annotation\Mapping\Inject("UserService")

     * @var  UserService

     */

    public $userService;

    /**

     * @RequestMapping("/")

     * @throws Throwable

     */

    public function index(): Response

    {

        /** @var Renderer $renderer */

        $renderer = Swoft::getBean('view');

        $content  = $renderer->render('home/index');

        return context()->getResponse()->withContentType(ContentType::HTML)->withContent($content);

    }



    /**

     * @RequestMapping("/hi")

     *

     * @return Response

     */

    public function hi()

    {

        return $this->userService->test();

    }

 调用service  里面使用协程 最终访问前端页面 立马返回了 数据 

UserService.php

<?php


namespace App\Service;

use function foo\func;

use Swoft\Bean\Annotation\Mapping\Bean;

use Swoft\Co;

use Swoft\Log\Helper\CLog;


/**

 * Class UserService

 * @Bean("UserService")

 * @package App\Service

 */

class UserService

{

    public function __construct()

    {
        
    }

     

    public function test()

    {

        Co::create(function(){

            Co::sleep(10);

            for($i=0;$i<10;$i++){

                CLog::info("hello: " . $i);

            }

        });



        Co::create(function(){

            Co::sleep(20);

            var_dump("world");

        });



        $id = Co::id();

        var_dump($id);

        $id = Co::tid();

        var_dump($id);

        return "nihao";

    }

}

  

过了十秒 和二十秒后分别打印出了数据

 

 

改为帮助函数 

sgo(function(){
   Co::sleep(10);
   for($i=0;$i<10;$i++){
      CLog::info("hello");
   }

});

srun

启动协程并等待执行结束。

public function test()
{
   srun(function(){
      sgo(function(){

         for($i=0;$i<10;$i++){
            Co::sleep(1);
            CLog::info("hello: " . $i);
         }

      });

      sgo(function(){
         for($i=0;$i<10;$i++){
            Co::sleep(1);
            CLog::warning("hello: " . $i);
         }
      });

      return true;

     });


   $id = Co::id();
   var_dump($id);
   $id = Co::tid();
   var_dump($id);
   return "test";    // 最先返回, 早于 srun
 }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

戴国进

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值