laravel框架整合workerman

来源:互联网 发布:php判断微信是否关注 编辑:程序博客网 时间:2024/05/20 23:39

配置

首先运行命令检测当前cli环境是否支持:

  1. curl -Ss http://www.workerman.net/check.php | php
  1. php -m //查看当前cli环境php模块

某些集成环境cli的配置文件和浏览器的配置文件路径不同,如mamppro.cli下运行php --ini查看

composer安装workerman

  1. cd your_path/laravel_program
  2. composer require workerman/workerman

artisan command实现

因为workerman服务启动是基于cli命令行模式,所以我们得用laravel的artisan来实现.

创建command

以下例子是创建一个简单的httpserver.其他服务请查看官方文档.

  1. php artisan make:command WorkermanHttpserver

laravel5.3改成command了,5.2 5.1 是console

进入App\Console\Commands目录下

  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Workerman\Worker;
  5. use App;
  6. class WorkermanHttpServer extends Command
  7. {
  8.  protected $httpserver;
  9.  /**
  10.  * The name and signature of the console command.
  11.  *
  12.  * @var string
  13.  */
  14.  protected $signature = 'workerman:httpserver {action} {--daemonize}';
  15.  /**
  16.  * The console command description.
  17.  *
  18.  * @var string
  19.  */
  20.  protected $description = 'workerman httpserver';
  21.  /**
  22.  * Create a new command instance.
  23.  *
  24.  * @return void
  25.  */
  26.  public function __construct()
  27.  {
  28.  parent::__construct();
  29.  }
  30.  /**
  31.  * Execute the console command.
  32.  *
  33.  * @return mixed
  34.  */
  35.  public function handle()
  36.  {
  37.  //因为workerman需要带参数 所以得强制修改
  38.  global $argv;
  39.  $action=$this->argument('action');
  40.  if(!in_array($action,['start','stop'])){
  41.  $this->error('Error Arguments');
  42.  exit;
  43.  }
  44.  $argv[0]='workerman:httpserver';
  45.  $argv[1]=$action;
  46.  $argv[2]=$this->option('daemonize')?'-d':'';
  47.  $this->httpserver=new Worker('http://0.0.0.0:8080');
  48.  // App::instance('workerman:httpserver',$this->httpserver);
  49.  $this->httpserver->onMessage=function($connection,$data){
  50.  $connection->send('laravel workerman hello world');
  51.  };
  52.  Worker::runAll();
  53.  }
  54. }

注册command

App\Console\Kernel.php文件添加刚才创建的command

  1. protected $commands = [
  2.  Commands\WorkermanHttpServer::class
  3. ];

运行

  1. #debug运行
  2. php artisan workerman:httpserver start
  3. #常驻后台运行
  4. php artisan workerman:httpserver start --daemonize

转至:

https://www.bandari.net/blog/19