>  기사  >  백엔드 개발  >  라라벨 큐 서비스

라라벨 큐 서비스

高洛峰
高洛峰원래의
2016-11-15 14:23:301049검색

QueueServiceProvider

라라벨의 다양한 서비스 등록 대부분은 다양한 ServiceProvider를 통해 바인딩되며 큐 서비스도 예외는 아닙니다. 네임스페이스 IlluminateQueueQueueServiceProvider 파일을 열고 등록 방법인

public function register()
{
   // 注册队列管理器 一旦实例化,为队列连接器注册各种解析器,这些连接器负责创建接受队列配置和实例化各种不同队列处理的类。
   // 按照配置文件注册一个默认连接方式 在此使用 redis
    $this->registerManager();
   // 注册队列各种命令 队列连接 重启等。
    $this->registerWorker();
   // 注册队列监听命令
    $this->registerListener();
   // 5.1后弃用
    $this->registerSubscriber();
   // 注册队列失败处理
    $this->registerFailedJobServices();
   // Register the Illuminate queued closure job. 什么用,后面再看。
    $this->registerQueueClosure();
}
작업 생성 및 할당

php artisan make:job SendReminderEmail
큐 작업 클래스는 문서에 따라 생성됩니다. 이 클래스는 네임스페이스AppJobsJob을 상속하고 SelfHandling 및 ShouldQueue 인터페이스를 구현합니다. 사용에 대한 규정은 없습니다(지금은 건너뛰세요). 삭제, 재시도, 지연 등과 같은 대기열 작업에 대한 다양한 작업을 구현하는 두 가지 특성에 중점을 둡니다.

작업을 할당할 때 실제로는 IlluminateBus 아래 Dispatcher 클래스의 디스패처 메서드인 보조 함수 디스패치를 ​​사용합니다.

public function dispatch($command, Closure $afterResolving = null)
{    

    if ($this->queueResolver && $this->commandShouldBeQueued($command)) {
        // 队列执行
        return $this->dispatchToQueue($command);
    } else {
        // 立即执行
        return $this->dispatchNow($command, $afterResolving);
    }
}
protected function commandShouldBeQueued($command)
{
    if ($command instanceof ShouldQueue) {  // 就这用。。
        return true;
    }

    return (new ReflectionClass($this->getHandlerClass($command)))->implementsInterface(
        'Illuminate\Contracts\Queue\ShouldQueue'
    );
}
여기서 먼저

를 살펴보겠습니다. IlluminateBusBusServiceProvider
public function register()
{
    $this->app->singleton('Illuminate\Bus\Dispatcher', function ($app) {
        return new Dispatcher($app, function () use ($app) {

        // 'queue.connection' => 'Illuminate\Contracts\Queue\Queue', 再回看 QueueServiceProvider 的 registerManager 方法,就很清晰了。

            return $app['Illuminate\Contracts\Queue\Queue']; // 默认队列连接
        });
    });
}
dispatchToQueue

public function dispatchToQueue($command)
{
    $queue = call_user_func($this->queueResolver); // 在此为设置的默认值 将实例化 RedisQueue
    
    // 异常则抛出!
    if (! $queue instanceof Queue) {
        throw new RuntimeException('Queue resolver did not return a Queue implementation.');
    }
    if (method_exists($command, 'queue')) {
        // 可以自定义
        return $command->queue($queue, $command);
    } else {
        // 在此使用的是进入队列方式  最终结果类似 $queue->push(); 看 RedisQueue 下的 push 方法。
        return $this->pushCommandToQueue($queue, $command);
    }
}
를 보면 위 작업이 대기열에 들어가는 전체 과정을 이해할 수 있습니다. 작업 대기열 제거는 어떻습니까? php artisan queue:work 명령문을 실행하여 큐를 모니터링하는 것을 문서에서 볼 수 있습니다. 네임스페이스 IlluminateQueueConsoleWorkCommand::fire()를 살펴보겠습니다. 매우 늦은 밤입니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.