dashbitco / broadway_rabbitmq

A Broadway producer for RabbitMQ
193 stars 42 forks source link

Working dead letter example #95

Closed lpender closed 3 years ago

lpender commented 3 years ago

Hi,

I'm happy to be working on an academic project involving criminal justice reform using Elixir and Broadway RabbitMQ!

This started out as an issue but as I did more and more research, it is more of an example.

However it is sort of an issue, in that it's not totally clear how dead-letter configuration works in the docs, and I think it would be helpful to add an example.

Here is the code--I wanted to share a method so that others may benefit. Happy to create a PR if that's helpful as well.

Thanks!

This will send failed messages to the my_queue_error queue on the default exchange.

def declare_queues do
    {:ok, connection} = AMQP.Connection.open()
    {:ok, channel} = AMQP.Channel.open(connection)
    AMQP.Queue.declare(channel, "my_queue_error", durable: true)
    AMQP.Queue.declare(channel, "my_queue",
      durable: true,
      arguments: [
        {"x-dead-letter-exchange", :longstr, ""},
        {"x-dead-letter-routing-key", :longstr, "my_queue_error"}
      ]
    )
end

def handle_message(_, message, _) do
    try do
      data = Jason.decode!(message, keys: :atoms)
      do_something_with!(message)
      message
    rescue
      e in RuntimeError ->
        message
        |> Broadway.Message.failed(e.message)
    end
end
josevalim commented 3 years ago

Please do send a PR! Note you don't need the rescue though, Broadway will automatically mark it as failed if it raises. :)