如何在command中调用job任务
1. 运行环境 centos7
1). 当前使用的 Laravel 版本? 11.44.7
2). 当前使用的 php/php-fpm 版本?8.3.3
业务描述
第三方应用,推送消息到redis中cdr
频道,laravel监听到消息之后,调用AsrJob
问题定位
1、fpm
下调用AsrJob是正常的,redis
中有队列数据
2、command
调用,在redis
中没有队列数据
业务代码如下
<?php
namespace App\Console\Commands;
use Redis;
use App\Events\CdrEvent;
use Illuminate\Console\Command;
class SubscribeRedisCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:subscribe-redis-command';
/**
* The console command description.
*
* @var string
*/
protected $description = '订阅redis频道';
/**
* 执行命令
* @return void
*/
public function handle(): void
{
$this->info('开始订阅redis频道');
$redis = app('redis');
$redis->setOption(Redis::OPT_READ_TIMEOUT, -1);
// 订阅多个频道
$redis->psubscribe(['cdr'], function (string $message) {
event(new CdrEvent($message));
});
}
}
文件AsrJob
代码如下:
<?php
namespace App\Jobs;
use App\Services\AsrService;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class AsrJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected string $type;
protected string|int $id;
/**
* 语音转文字服务
* @var AsrService
*/
protected AsrService $asrService;
public function __construct(string $type, string|int $id)
{
$this->id = $id;
$this->type = $type;
// $this->asrService = new AsrService();
info('AsrJob created', ['type' => $this->type, 'id' => $this->id]);
}
/**
* Execute the job.
*/
public function handle(): void
{
info($this->type, ['id' => $this->id]);
// $uuid = $this->asrService->translate($this->file);
// if ($uuid) {
// info('语音识别成功', ['uuid' => $uuid, 'file' => $this->file]);
// }
}
}
经过排查,发现通过command
调用job
在redis中没有任何数据,日志中只有[2025-06-17 16:13:34] local.INFO: AsrJob created {"type":"test","id":"123"}
但是在fpm下调用则是正常的。
fpm调用代码:
Route::get('/test', function() {
dispatch(new \App\Jobs\AsrJob('test', '123'));
return 'ok';
});
推荐文章: