当前位置: 首页 > 工具软件 > Workerman > 使用案例 >

laravel8集成workerman

汲利
2023-12-01

优点是 workerman与laravel共享代码, 能够使用laravel强大的功能写workerman

缺点: 速度可能不理想,; 不知道mysql连接使用laravel的数据库组件不知道 会不会断

-------------

首先执行  composer require workerman/workerman  安装workerman

创建command

php artisan make:command WorkermanHttpserver

生成文件:

app/Console/Commands/WorkermanHttpserver.php

修改代码为:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Workerman\Worker;
use App;
use Illuminate\Support\Facades\DB;

class WorkermanHttpserver extends Command
{
    protected $httpserver;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'workerman:httpserver {action} {--daemonize}';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'workerman httpserver';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //因为workerman需要带参数 所以得强制修改
        global $argv;
        $action = $this->argument('action');
        if (!in_array($action, ['start','stop'])) {
            $this->error('Error Arguments');
            exit;
        }
        $argv[0] = 'workerman:httpserver';
        $argv[1] = $action;
        $argv[2] = $this->option('daemonize') ? '-d' : '';
        $this->httpserver = new Worker('http://0.0.0.0:8080');
        // App::instance('workerman:httpserver',$this->httpserver);
        $this->httpserver->onMessage = function ($connection, $data) {
            $user = DB::table('users')->first();
            //$user = json_decode(json_encode($user), 1);
            $connection->send(json_encode($user));
            $connection->send('laravel workerman hello world');
        };
        Worker::runAll();
    }
}

需要在linux下运行, 如何配置lamp环境和怎么安装workerman, 请自行百度, 我的博客里面也有

调试模式运行:

php artisan workerman:httpserver start

后台运行:

php artisan workerman:httpserver status --daemonize

我的是linux虚拟机

浏览器访问:

http://192.168.56.101:8080/

得到的是一个json串

参考:

laravel 整合WorkerMan - 花泪哲 - 博客园

完整示例: 注意分支

tbqlarapps/laravel   分支: tbq-v8.6-workerman1

 类似资料: