laravel8框架集成RabbitMQ队列驱动程序
环境介绍
rabbitmq服务使用:CloudAMQP
在laravel框架中安装使用步骤
rabbitmq扩展包git:
https://github.com/vyuldashev/laravel-queue-rabbitmq
composer安装rabbitmq扩展包
composer require vladimir-yuldashev/laravel-queue-rabbitmq
.env文件信息获取配置:
QUEUE_CONNECTION=rabbitmq
#需要申请
RABBITMQ_HOST=shark.rmq.cloudamqp.com
RABBITMQ_PORT=5672
RABBITMQ_USER=xxx
RABBITMQ_PASSWORD=xxx
RABBITMQ_VHOST=xxx
RABBITMQ_QUEUE=admin_queue #自定义
队列配置:config/queue.php
'connections' => [
'rabbitmq' => [
'driver' => 'rabbitmq',
'queue' => env('RABBITMQ_QUEUE', 'default'),
'connection' => PhpAmqpLib\Connection\AMQPLazyConnection::class,
'hosts' => [
[
'host' => env('RABBITMQ_HOST', '127.0.0.1'),
'port' => env('RABBITMQ_PORT', 5672),
'user' => env('RABBITMQ_USER', 'guest'),
'password' => env('RABBITMQ_PASSWORD', 'guest'),
'vhost' => env('RABBITMQ_VHOST', '/'),
],
],
'options' => [
'ssl_options' => [
'cafile' => env('RABBITMQ_SSL_CAFILE', null),
'local_cert' => env('RABBITMQ_SSL_LOCALCERT', null),
'local_key' => env('RABBITMQ_SSL_LOCALKEY', null),
'verify_peer' => env('RABBITMQ_SSL_VERIFY_PEER', true),
'passphrase' => env('RABBITMQ_SSL_PASSPHRASE', null),
],
'queue' => [
'job' => VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Jobs\RabbitMQJob::class,
],
],
/*
* Set to "horizon" if you wish to use Laravel Horizon.
*/
'worker' => env('RABBITMQ_WORKER', 'default'),
],
],
队列使用
生成任务类
php artisan make:job TestJob
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class TestJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private array $data = [];
public function __construct($data)
{
$this->data = $data;
}
public function handle()
{
sleep(3);
var_dump($this->data);
}
}
ps:
在队列处理任务时,会调用 handle 方法,而这里我们也可以通过 handle 方法的参数类型提示,让 Laravel 的 服务容器 自动注入依赖对象。
如果你想完全控制容器如何将依赖对象注入至 handle 方法,可以使用容器的 bindMethod 方法。
bindMethod 方法接受一个任务和容器的回调。
虽然可以直接在回调中可以调用 handle 方法,但建议应该从 service provider 调用为佳:
#官方写法
use App\Jobs\ProcessPodcast;
$this->app->bindMethod(ProcessPodcast::class.'@handle', function ($job, $app) {
return $job->handle($app->make(AudioProcessor::class));
});
\App::bindMethod(TestJob::class . '@handle', function ($job){
return $job->handle();
});
//php7.4写法
\App::bindMethod(ProductCreated::class . '@handle', fn($job) => $job->handle());
任务分发并指定队列
use App\Jobs\TestJob;
TestJob::dispatch(['title'=>'testjob'])->onQueue('admin_queue');
运行启动
#--host=0.0.0.0指定外网,不然访问不了
#--port=8080指定端口
php artisan serve --host=0.0.0.0 --port=8080
php artisan queue:work
相关文章