Laravel使用RabbitMQ的方法示例

时间:2021-05-26

导语

RabbitMQ 想必大家都有了解,不做多介绍来。这里实现的是用 RabbitMQ 作为 Larvel 队列的驱动,替代 Redis。下面以 Laradock 中安装示例。

安装

  • 切换到laradock 目录,将.env 中关于INSTALL_AMQP 的值修改为true
  • docker-compose stop workspace php-fpm php-worker
  • docker-compose build workspace php-fpm php-worker rabbitmq
  • docker-compose up -d workspace php-fpm php-worker rabbitmq
  • 扩展包安装以及配置

  • 进入到workspace 容器中,在项目目录安装扩展包composer require vladimir-yuldashev/laravel-queue-rabbitmq
  • 接下来在config/queue.php 文件中connections 添加rabbitmq 配置,根据情况自行修改
  • 'rabbitmq' => [ 'driver' => 'rabbitmq', /* * Set to "horizon" if you wish to use Laravel Horizon. */ 'worker' => env('RABBITMQ_WORKER', 'default'), 'dsn' => env('RABBITMQ_DSN', null), /* * Could be one a class that implements \Interop\Amqp\AmqpConnectionFactory for example: * - \EnqueueAmqpExt\AmqpConnectionFactory if you install enqueue/amqp-ext * - \EnqueueAmqpLib\AmqpConnectionFactory if you install enqueue/amqp-lib * - \EnqueueAmqpBunny\AmqpConnectionFactory if you install enqueue/amqp-bunny */ 'factory_class' => Enqueue\AmqpLib\AmqpConnectionFactory::class, 'host' => env('RABBITMQ_HOST', '127.0.0.1'), 'port' => env('RABBITMQ_PORT', 5672), 'vhost' => env('RABBITMQ_VHOST', '/'), 'login' => env('RABBITMQ_LOGIN', 'guest'), 'password' => env('RABBITMQ_PASSWORD', 'guest'), 'queue' => env('RABBITMQ_QUEUE', 'default'), 'options' => [ 'exchange' => [ 'name' => env('RABBITMQ_EXCHANGE_NAME'), /* * Determine if exchange should be created if it does not exist. */ 'declare' => env('RABBITMQ_EXCHANGE_DECLARE', true), /* * Read more about possible values at https:///ssl.html */ 'ssl_params' => [ 'ssl_on' => env('RABBITMQ_SSL', false), '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), ],],

    在.env 中修改QUEUE_CONNECTION 为rabbitmq ,并添加以下值

    RABBITMQ_WORKER=horizonRABBITMQ_HOST=rabbitmqRABBITMQ_PORT=5672RABBITMQ_LOGIN=guestRABBITMQ_PASSWORD=guestRABBITMQ_QUEUE=default

    有两个值说明一下,因为是在 Laradock 中,所以RABBITMQ_HOST 设置为rabbitmq ;如果之前使用了Laravel Horizon,那么RABBITMQ_WORKER 的设置为horizon 就可以了。

    参考资料:laravel-queue-rabbitmq

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

    声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

    相关文章