美文网首页
laravel 启动swoole

laravel 启动swoole

作者: jooohnny | 来源:发表于2018-01-10 16:18 被阅读0次

使用laravel artisan 生成swoole 启动命令

php artisan make:command Swoole

在生成的app/Console/Command/Swoole.php中

public function handle()
{
    $arg=$this->argument('action');
    switch($arg)
     {
         case 'start':
             $this->info('swoole observer started');
             $this->start();
             break;
     }
}
private function start()
{
    $this->serv=new \swoole_server("127.0.0.1",9501);
    $this->serv->set(array(
        'worker_num' => 8,
        'daemonize' => false,
        'max_request' => 10000,
        'dispatch_mode' => 2,
        'debug_mode'=> 1
    ));
    $this->serv->on('Start', array($this->swoole_handle, 'onStart'));
    $this->serv->on('Connect', array($this->swoole_handle, 'onConnect'));
    $this->serv->on('Receive', array($this->swoole_handle, 'onReceive'));
    $this->serv->on('Close', array($this->swoole_handle, 'onClose'));
    $this->serv->start();
}

注册命令

app/Console/Kernel.php

protected $commands = [
    Commands\Swoole::class,
];

这里的$this->swoole_handle,是我使用laravel的ioc调用的,因为不想所有的方法都在这个文件上所以有个专门处理的SwooleHandle类,这样在这里使用laravel的Redis,orm。
app/Handle/SwooleHandle.php

<?php 
namespace App\Handle;

use Redis;
use App\Repositories\RoomRepositoryEloquent;

class SwooleHandle  
{
    public function __construct()
    {
        
    }
    public function onOpen($serv, $request)
    {
        echo 'onOpen'; 
    }
    public function onMessage($serv,$frame)
    {
        echo 'onMessage';
    }
    public function onClose($serv,$fd)
    {
        echo 'onClose';
    }
    
}
?>

注册SwooleHandle.class

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\handle\SwooleHandle;

class SwooleHandleServiceProvider extends ServiceProvider
{
/**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
    public function register()
    {
        $this->app->singleton('swoole',function(){
            return new SwooleHandle();
        });
    }
}

命令行模式下执行命令开启Swoole服务

php artisan swoole start

相关文章

网友评论

      本文标题:laravel 启动swoole

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