总觉得这样写不正确?

bobshipwood

问题描述

public function startWorker2()
    {
        $worker = new Worker();
        $worker->count = 4;
        $worker->onWorkerStart = function ($worker) {
            try {
                // 为每个子进程创建独立的 MQTT 客户端实例
                $mqttClient = new \Workerman\Mqtt\Client(env('MQTT_URL'), ['client_id' => "sy-mqtt-client-".mt_rand(), 'username' => env('MQTT_USERNAME'), 'password' => env('MQTT_PASSWORD')]);
                $mqttClient->connect();
                switch ($worker->id) {
                    case 0:
                        app()->make(\App\Services\DeviceModelService::class,  ['mqttClient' => $mqttClient]); // 执行485设备定时采集数据
                        break;
                    case 1:
                        app()->make(\App\Services\ModelReceiveService::class,  ['mqttClient' => $mqttClient]); // 执行485设备收集数据
                        break;
                    default:
                        break;
                }
            } catch (\Exception $e) {
//                Log::error("An error occurred in Worker_" . $worker->id . ": " . $e->getMessage(), [ // 记录错误日志
//                    'worker_id' => $worker->id,
//                    'exception' => $e,
//                ]);
                echo "An error occurred in Worker_" . $worker->id . ": " . $e->getMessage();
                echo $e->getFile() . $e->getLine();
            }
        };
    }

为此你搜索到了哪些方案及不适用的原因

问题出现在这里, app()->make(\App\Services\DeviceModelService::class, ['mqttClient' => $mqttClient]); 怎么能确保里面的mqtt一定是这个进程所对应的mqtt呢?

72 0 0
0个回答

×
🔝