happyr/mq2php-bundle

无需使用cron即可自动从消息队列中消费消息。与SimpleBus配合使用效果极佳

安装次数: 23,650

依赖项: 1

建议者: 0

安全性: 0

星标: 1

关注者: 2

分支: 2

开放问题: 0

类型:symfony-bundle

0.3.3 2018-01-29 12:17 UTC

This package is auto-updated.

Last update: 2024-08-25 06:51:01 UTC


README

Latest Version Software License Build Status Code Coverage Quality Score Total Downloads

此捆绑包是SimpleBus和mq2php之间的桥梁。它可以与SimpleBusAsynchronousBundle一起使用,使异步消息独立于cron作业来消费消息。相反,我们利用PHP-FPM的力量来调度工作负载和资源。

从队列中消费消息

我们不希望运行cron命令来从队列中消费消息,原因有两个。创建新线程需要大量的计算机资源,如果我们只做一项任务,将会产生很多开销。第二个原因是,我们想要能够进行资源调度。使用cron作业,我们说“不管当前负载如何,在下一分钟消费此消息”。相反,我们希望做一些像“尽可能快地消费此消息”的事情。

这些问题的解决方案并不新鲜。实际上,这正是PHP-FPM要解决的问题。我们只需要一种从消息队列中拉取消息并将其提供给PHP-FPM的方式。

这正是mq2php发挥作用的地方。它是一个Java应用程序,将在后台运行。Java被首选,因为它被设计成可以永远运行。(与PHP相比,PHP不应运行超过30秒。)

安装

获取mq2php.jar版本0.5.0或更高版本,并使用以下命令启动应用程序:

java -Dexecutor=fastcgi -DmessageQueue=rabbitmq -DqueueNames=asynchronous_commands,asynchronous_events -jar mq2php.jar

当您在生产服务器上使用它时,应考虑使用init脚本。

安装并启用此捆绑包

composer require happyr/mq2php-bundle
class AppKernel extends Kernel
{
  public function registerBundles()
  {
    $bundles = array(
        // ...
        new Happyr\Mq2phpBundle\HappyrMq2phpBundle(),
        new SimpleBus\AsynchronousBundle\SimpleBusAsynchronousBundle(),
    }
  }
}

配置

// config.yml

old_sound_rabbit_mq:
  producers:
    asynchronous_commands:
      connection:       default
      exchange_options: { name: 'asynchronous_commands', type: direct }
      queue_options:    { name: 'asynchronous_commands' }

    asynchronous_events:
      connection:       default
      exchange_options: { name: 'asynchronous_events', type: direct }
      queue_options:    { name: 'asynchronous_events' }

simple_bus_rabbit_mq_bundle_bridge:
  commands:
    producer_service_id: old_sound_rabbit_mq.asynchronous_commands_producer
  events:
    producer_service_id: old_sound_rabbit_mq.asynchronous_events_producer
    
happyr_mq2php:
  enabled: true
  command_queue: 'asynchronous_commands' # The name of the RabbitMQ queue for commands
  event_queue: 'asynchronous_events' # The name of the RabbitMQ queue for events
  message_headers: 
    fastcgi_host: localhost
    fastcgi_port: 9000
    dispatch_path: "%kernel.root_dir%/dispatch-message.php"

HTTP执行器

如果您不使用fastcgi(例如PHP-FPM),您可以使用HTTP。

happyr_mq2php:
  message_headers: 
    http_url: https://example.com/dispatch-message.php

Shell执行器

在调试时,您可能想使用shell执行器。这将要求mq2php消耗更多的CPU资源,因为为每条消息启动一个新的进程是非常昂贵的。

happyr_mq2php:
  message_headers: 
    dispatch_path: "%kernel.root_dir%/dispatch-message.php"

验证消息

如果您想确保您的消息有效且来自您的应用程序,您应该定义一个密钥。此密钥用于散列消息,然后在接收端验证散列。如果您使用多个应用程序,请确保它们都具有相同的密钥。

happyr_mq2php:
  secret_key: '4e10upv918856xxp7g9c'

减少消息数量

在SimpleBus文档中,您可能会发现所有事件都将同步处理,然后异步处理。这意味着对于应用程序发出的每个事件,都会有异步消息。如果您想减少消息数量,您可以配置SimpleBus AsyncBundle只处理标记为异步的事件。

simple_bus_asynchronous:
  events:
    strategy: 'predefined'