RabbitMQ 和 RabbitMQBundle 路由键配置到多消费者

RabbitMQ and RabbitMQBundle routing keys configuration to multi consumer

我在 Symfomy4 中使用 RabbitMqBundle。

我想要实现的是发布一条消息(在我的例子中是一条通知)并通过路由键选择是将消息存储在 Db 中还是通过电子邮件发送或两者都发送。

我专注于topic exchange 但我不知道如何达到这个目标,也许我没有完全理解 RabbitMQ 的机制,但我'我对它完全陌生。

这是我的配置

old_sound_rabbit_mq:
  connections:
    default:
      #url: '%env(RABBITMQ_URL)%'
      url: 'amqp://guest:guest@localhost:5672'
      vhost:    '/'
      lazy:     false
      connection_timeout: 3
      read_write_timeout: 3
  producers:
    notifications:
      connection: default
      exchange_options: {name: 'notifications', type: topic}
  consumers:
    store_notifications:
      connection: default
      exchange_options: {name: 'notifications', type: topic}
      queue_options:
        name: 'notifications'
        routing_keys:
        - 'notification.store'
        # - 'notification.*' # this will match everything
      callback: App\Consumer\Notification\DbHandler
    email_notifications:
      connection: default
      exchange_options: {name: 'notifications', type: topic}
      queue_options:
        name: 'notifications'
        routing_keys:
        - 'notification.email'
      callback: App\Consumer\Notification\EmailHandler

在这种情况下,我可以只向路由键之一发布消息:notification.storenotification.email

我想要像 publish($msg, ['notification.store', 'notification.email']) 这样的东西,但我知道我可以做一个 consumer听多个路由键和通配符,但我不知道如何配置它。

这可能吗?

我认为你可以这样做:

  • 如果只想存放DB,路由键为:notification.store
  • 如果你只想发邮件,路由键是:notification.email
  • 如果你想两者都做,路由键是:notification.both

然后,您的队列应该使用这些路由键绑定到交换器:

  • store_notifications: [notification.store, notification.both]
  • email_notifications: [notification.email, notification.both]

通过这样做,如果带有路由 notification.store 的邮件只转到 store_notificationsnotification.email 只转到 email_notifications。但是带有路由 notification.both 的消息会进入两个队列。

配置:

  consumers:
    store_notifications:
      connection: default
      exchange_options: {name: 'notifications', type: topic}
      queue_options:
        name: 'notifications'
        routing_keys:
        - 'notification.store'
        - 'notification.both'
      callback: App\Consumer\Notification\DbHandler
    email_notifications:
      connection: default
      exchange_options: {name: 'notifications', type: topic}
      queue_options:
        name: 'notifications'
        routing_keys:
        - 'notification.email'
        - 'notification.both'
      callback: App\Consumer\Notification\EmailHandler

希望这对您有所帮助。